forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
managing-duplicates-in-list-t-in-dart.dart
48 lines (36 loc) · 1.26 KB
/
managing-duplicates-in-list-t-in-dart.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Want to support my work 🤝? https://buymeacoffee.com/vandad
extension Duplicates<T> on List<T> {
void addAllByAvoidingDuplicates(Iterable<T> values) =>
replaceRange(0, length, {
...([...this] + [...values])
});
int get numberOfDuplicates => length - {...this}.length;
bool get containsDuplicates => numberOfDuplicates > 0;
List<T> get uniques => [
...{...this}
];
void removeDuplicates() => replaceRange(
0,
length,
uniques,
);
List<T> get duplicates => [
for (var i = 0; i < length; i++)
[...this].skip(i + 1).contains(this[i]) ? this[i] : null
].whereType<T>().toList();
}
void testIt() {
final values = [3, 2, 10, 30, 40, 30, 100, 10];
assert(values.numberOfDuplicates == 2);
assert(values.containsDuplicates == true);
assert(values.uniques.length == values.length - 2);
print(values.uniques); // [3, 2, 10, 30, 40, 100]
values.removeDuplicates();
print(values); // [3, 2, 10, 30, 40, 100]
assert(values.numberOfDuplicates == 0);
assert(!values.containsDuplicates);
assert(values.duplicates.isEmpty);
values.addAllByAvoidingDuplicates([3, 2, 10, 200]);
print(values); // [3, 2, 10, 30, 40, 100, 200]
assert(values.containsDuplicates == false);
}