refactor: FilterMap extension

This commit is contained in:
Lukas Lihotzki 2021-07-19 19:43:20 +02:00
parent c10a98ff35
commit bad334d441
2 changed files with 16 additions and 15 deletions

View File

@ -23,6 +23,7 @@
import 'package:matrix_api_lite/src/utils/logs.dart';
import '../../utils/filter_map_extension.dart';
import '../../utils/try_get_map_extension.dart';
import '../basic_event.dart';
@ -31,11 +32,6 @@ extension RoomEncryptedContentBasicEventExtension on BasicEvent {
RoomEncryptedContent.fromJson(content);
}
/// Convert Nullable iterable of MapEntries to Map
extension ToMap<T1, T2> on Iterable<MapEntry<T1, T2>> {
Map<T1, T2> toMap() => Map.fromEntries(this);
}
class RoomEncryptedContent {
String algorithm;
String senderKey;
@ -53,16 +49,7 @@ class RoomEncryptedContent {
// filter out invalid/incomplete CiphertextInfos
ciphertextOlm = json
.tryGet<Map<String, dynamic>>('ciphertext', TryGet.silent)
?.entries
.map((e) {
try {
return MapEntry(e.key, CiphertextInfo.fromJson(e.value));
} catch (_) {
return null;
}
})
.whereType<MapEntry<String, CiphertextInfo>>()
.toMap();
?.catchMap((k, v) => MapEntry(k, CiphertextInfo.fromJson(v)));
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};

View File

@ -0,0 +1,14 @@
extension FilterMap<K, V> on Map<K, V> {
Map<K2, V2> filterMap<K2, V2>(MapEntry<K2, V2>? Function(K, V) f) =>
Map.fromEntries(
entries.map((e) => f(e.key, e.value)).whereType<MapEntry<K2, V2>>());
Map<K2, V2> catchMap<K2, V2>(MapEntry<K2, V2> Function(K, V) f) =>
filterMap((k, v) {
try {
return f(k, v);
} catch (_) {
return null;
}
});
}