Skip to content

Commit

Permalink
Merge pull request #78 from acherkashyn/master
Browse files Browse the repository at this point in the history
Add KtMap.forEach() method.
  • Loading branch information
passsy authored Feb 20, 2019
2 parents 06da362 + 34edd0c commit 05264f6
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 1 deletion.
9 changes: 9 additions & 0 deletions lib/src/collection/extension/map_extensions_mixin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,15 @@ abstract class KtMapExtensionsMixin<K, V>
return mutableMapFrom(map);
}

@override
void forEach(Function(K key, V value) action) {
assert(() {
if (action == null) throw ArgumentError("action can't be null");
return true;
}());
entries.forEach((entry) => action(entry.key, entry.value));
}

@override
String toString() {
return entries.joinToString(
Expand Down
7 changes: 7 additions & 0 deletions lib/src/collection/kt_map.dart
Original file line number Diff line number Diff line change
Expand Up @@ -254,4 +254,11 @@ abstract class KtMapExtension<K, V> {
* The returned map preserves the entry iteration order of the original map.
*/
KtMutableMap<K, V> toMutableMap();

/**
* Performs given [action] on each key/value pair from this map.
*
* [action] must not be null.
*/
void forEach(Function(K key, V value) action);
}
2 changes: 1 addition & 1 deletion test/collection/list_extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ void testList(
expect(list.takeLast(2).toList(), listFrom([1, null]));
});
});

group("takeLastWhile", () {
test("take no elements returns empty", () {
final list = listOf(1, 2, 3, 4);
Expand Down
27 changes: 27 additions & 0 deletions test/collection/map_extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,33 @@ void testMap(KtMap<K, V> Function<K, V>() emptyMap,
expect(map.size, 2);
});
});

group("forEach", () {
test("forEach", () {
final result = mutableListOf<String>();
final map = mapFrom({
1: "Bulbasaur",
2: "Ivysaur",
3: "Stegosaur",
});
map.forEach((number, value) => result.add('$number-$value'));
if (ordered) {
expect(result.size, 3);
expect(result[0], "1-Bulbasaur");
expect(result[1], "2-Ivysaur");
expect(result[2], "3-Stegosaur");
} else {
expect(result.size, 3);
expect(result.toSet(),
listOf("1-Bulbasaur", "2-Ivysaur", "3-Stegosaur").toSet());
}
});

test("action must be non null", () {
final e = catchException<ArgumentError>(() => emptyMap().forEach(null));
expect(e.message, allOf(contains("null"), contains("action")));
});
});
}

class ThirdPartyMap<K, V>
Expand Down

0 comments on commit 05264f6

Please sign in to comment.