Skip to content

Commit

Permalink
Create compactmap-on-map-in-dart.dart
Browse files Browse the repository at this point in the history
  • Loading branch information
vandadnp committed Jul 19, 2022
1 parent acf65a5 commit e8cfb80
Showing 1 changed file with 50 additions and 0 deletions.
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}
}

0 comments on commit e8cfb80

Please sign in to comment.