-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create compactmap-on-map-in-dart.dart
- Loading branch information
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
50 changes: 50 additions & 0 deletions
50
tipsandtricks/compactmap-on-map-in-dart/compactmap-on-map-in-dart.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
// š¦ 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 | ||
// š¤ Want to support my work? https://buymeacoffee.com/vandad | ||
|
||
import 'dart:developer' as dev show log; | ||
|
||
// log | ||
extension Log on Object { | ||
void log() { | ||
dev.log(toString()); | ||
} | ||
} | ||
|
||
extension CompactMap<K, V> on Map<K, V> { | ||
Map<K2, V2> compactMap<K2, V2>( | ||
MapEntry<K2, V2>? Function(MapEntry<K, V>) f, | ||
) { | ||
final result = <K2, V2>{}; | ||
for (final entry in entries) { | ||
final newEntry = f(entry); | ||
if (newEntry != null) { | ||
result[newEntry.key] = newEntry.value; | ||
} | ||
} | ||
return result; | ||
} | ||
} | ||
|
||
final values = { | ||
'first_name': 'Foo', | ||
'last_name': 'Bar', | ||
'age': 22, | ||
}; | ||
|
||
void testIt() { | ||
values.compactMap((entry) { | ||
if (entry.key == 'age') { | ||
return null; | ||
} else { | ||
return MapEntry( | ||
entry.key.toUpperCase(), | ||
entry.value, | ||
); | ||
} | ||
}).log(); // {FIRST_NAME: Foo, LAST_NAME: Bar} | ||
} |