Skip to content

Commit d204215

Browse files
committed
+ iterable distinct
1 parent 5b055d4 commit d204215

File tree

4 files changed

+54
-0
lines changed

4 files changed

+54
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export 'date_time_extensions.dart';
22
export 'future_extensions.dart';
3+
export 'iterable_extensions.dart';
34
export 'object_extensions.dart';
45
export 'string_extensions.dart';
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import 'dart:core';
2+
3+
import 'package:collection/collection.dart';
4+
5+
typedef Selector<T, K> = K Function(T selectFrom);
6+
7+
extension IterableExtensions<T> on Iterable<T> {
8+
/// Returns a set containing only distinct elements from the given collection.
9+
Set<T> distinct() {
10+
return toSet();
11+
}
12+
13+
/// Returns a list containing only elements from the given collection having distinct keys returned by the given [selector] function. If multiple elements have the same key, first element is returned.
14+
Iterable<T> distinctBy<K>(Selector<T,K> selector) {
15+
return groupBy<T, K>(this, selector)
16+
.values
17+
// ignore: avoid-unsafe-collection-methods, groupBy returns non-empty lists
18+
.map((e) => e.first);
19+
}
20+
}

packages/netglade_utils/pubspec.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ environment:
1212
dependencies:
1313
characters: ^1.2.0
1414
clock: ^1.0.0
15+
collection: ^1.0.0
1516
http: ^1.0.0
1617
mocktail: ^1.0.0
1718

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import 'package:netglade_utils/netglade_utils.dart';
2+
import 'package:test/test.dart';
3+
4+
void main() {
5+
group('distinct', () {
6+
test('distinct', () {
7+
expect([1, 2, 3].distinct(), equals({1, 2, 3}));
8+
});
9+
10+
test('with duplicates', () {
11+
expect([2, 4, 4, 5, 6, 6, 6].distinct(), equals({2, 4, 5, 6}));
12+
});
13+
14+
test('empty', () {
15+
expect(<int>[].distinct(), equals(<int>{}));
16+
});
17+
});
18+
19+
group('distinct by', () {
20+
test('distinct', () {
21+
expect([[1,3], [2,5], [3,3]].distinctBy((e) => e.firstOrNull), equals({[1,3], [2,5], [3,3]}));
22+
});
23+
24+
test('with duplicates', () {
25+
expect([[1,3], [2,5], [1,6], [1,0]].distinctBy((e) => e.firstOrNull), equals({[1,3], [2,5]}));
26+
});
27+
28+
test('empty', () {
29+
expect(<int>[].distinctBy((e) => e*e), equals(<int>{}));
30+
});
31+
});
32+
}

0 commit comments

Comments
 (0)