Skip to content

Commit

Permalink
Merge pull request #24 from netglade/story/iterable-distinct
Browse files Browse the repository at this point in the history
Add distinctBy iterable extension
  • Loading branch information
ivicicm authored Feb 12, 2024
2 parents 5b055d4 + aa3261d commit e09a893
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 1 deletion.
3 changes: 3 additions & 0 deletions packages/netglade_utils/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 1.3.0
- Add `distinctBy` to iterable extensions.

## 1.2.0
- Add `ifEmpty` and `ifBlank` to string extensions.
- Remove typedefs. (private)
Expand Down
1 change: 1 addition & 0 deletions packages/netglade_utils/lib/src/extensions/extensions.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export 'date_time_extensions.dart';
export 'future_extensions.dart';
export 'iterable_extensions.dart';
export 'object_extensions.dart';
export 'string_extensions.dart';
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import 'dart:core';

typedef Selector<T, K> = K Function(T selectFrom);

extension IterableExtensions<T> on Iterable<T> {
/// Returns an iterable 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.
Iterable<T> distinctBy<K>(Selector<T, K> selector) {
final result = <K, T>{};
for (final item in this) {
final _ = result.putIfAbsent(selector(item), () => item);
}

return result.values;
}
}
3 changes: 2 additions & 1 deletion packages/netglade_utils/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: netglade_utils
version: 1.2.0
version: 1.3.0
description: Dart utils used internally at netglade.
repository: https://github.com/netglade/flutter_core/tree/main/packages/netglade_utils
issue_tracker: https://github.com/netglade/flutter_core/issues
Expand All @@ -12,6 +12,7 @@ environment:
dependencies:
characters: ^1.2.0
clock: ^1.0.0
collection: ^1.0.0
http: ^1.0.0
mocktail: ^1.0.0

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import 'package:collection/collection.dart';
import 'package:netglade_utils/netglade_utils.dart';
import 'package:test/test.dart';

void main() {
group('distinct by', () {
test('distinct', () {
expect(
[
[1, 3],
[2, 5],
[3, 3],
].distinctBy((e) => e.firstOrNull),
equals({
[1, 3],
[2, 5],
[3, 3],
}),
);
});

test('with duplicates', () {
expect(
[
[1, 3],
[2, 5],
[1, 6],
[1, 0],
].distinctBy((e) => e.firstOrNull),
equals({
[1, 3],
[2, 5],
}),
);
});

test('empty', () {
expect(<int>[].distinctBy((e) => e * e), equals(<int>{}));
});
});
}

0 comments on commit e09a893

Please sign in to comment.