forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 1
/
where-clause-on-map-in-dart.dart
39 lines (32 loc) · 1.35 KB
/
where-clause-on-map-in-dart.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 🐦 Twitter https://twitter.com/vandadnp
// 🔵 LinkedIn https://linkedin.com/in/vandadnp
// 🎥 YouTube https://youtube.com/c/vandadnp
// 💙 Free Flutter Course https://linktr.ee/vandadnp
// 📦 11+ Hours Bloc Course https://youtu.be/Mn254cnduOY
// 🔶 7+ Hours MobX Course https://youtu.be/7Od55PBxYkI
// 🦄 8+ Hours RxSwift Coursde https://youtu.be/xBFWMYmm9ro
// 🤝 Want to support my work? https://buymeacoffee.com/vandad
import 'dart:developer' as devtools show log;
extension Log on Object {
void log() => devtools.log(toString());
}
extension DetailedWhere<K, V> on Map<K, V> {
Map<K, V> where(bool Function(K key, V value) f) => Map<K, V>.fromEntries(
entries.where((entry) => f(entry.key, entry.value)),
);
Map<K, V> whereKey(bool Function(K key) f) =>
{...where((key, value) => f(key))};
Map<K, V> whereValue(bool Function(V value) f) =>
{...where((key, value) => f(value))};
}
typedef Age = int;
typedef Name = String;
const Map<Name, Age> people = {'John': 20, 'Mary': 21, 'Peter': 22};
void testIt() {
// {Peter: 22}
people.where((key, value) => key.length > 4 && value > 20).log();
// {John: 20, Mary: 21}
people.whereKey((key) => key.length < 5).log();
// {John: 20, Peter: 22}
people.whereValue((value) => value.isEven).log();
}