Skip to content

Commit aa3261d

Browse files
committed
- distinct, more optimap distinctBy implementation
1 parent d9b0e8b commit aa3261d

File tree

3 files changed

+8
-25
lines changed

3 files changed

+8
-25
lines changed

packages/netglade_utils/CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
## 1.3.0
2-
- Add `distinct` and `distinctBy` to iterable extensions.
2+
- Add `distinctBy` to iterable extensions.
33

44
## 1.2.0
55
- Add `ifEmpty` and `ifBlank` to string extensions.
Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,16 @@
11
import 'dart:core';
22

3-
import 'package:collection/collection.dart';
4-
53
typedef Selector<T, K> = K Function(T selectFrom);
64

75
extension IterableExtensions<T> on Iterable<T> {
8-
Iterable<T> distinct() {
9-
return toSet();
10-
}
11-
126
/// Returns an iterable containing only elements from the given collection having distinct keys returned by the given [selector] function.
137
/// If multiple elements have the same key, first element is returned.
148
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);
9+
final result = <K, T>{};
10+
for (final item in this) {
11+
final _ = result.putIfAbsent(selector(item), () => item);
12+
}
13+
14+
return result.values;
1915
}
2016
}

packages/netglade_utils/test/src/extensions/iterable_extensions_test.dart

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,8 @@
1+
import 'package:collection/collection.dart';
12
import 'package:netglade_utils/netglade_utils.dart';
23
import 'package:test/test.dart';
34

45
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-
196
group('distinct by', () {
207
test('distinct', () {
218
expect(

0 commit comments

Comments
 (0)