nc-photos/lib/list_extension.dart

33 lines
944 B
Dart
Raw Normal View History

2021-04-10 06:28:12 +02:00
extension ListExtension<T> on List<T> {
/// Return a new list with only distinct elements
List<T> distinct() {
2021-09-15 08:58:06 +02:00
final s = <T>{};
return where((element) => s.add(element)).toList();
2021-04-10 06:28:12 +02:00
}
/// Return a new list with only distinct elements determined by [equalFn]
List<T> distinctIf(
bool Function(T a, T b) equalFn, int Function(T a) hashCodeFn) {
2021-09-15 08:58:06 +02:00
final s = <_DistinctComparator<T>>{};
return where((element) =>
s.add(_DistinctComparator<T>(element, equalFn, hashCodeFn))).toList();
}
2021-04-10 06:28:12 +02:00
Iterable<T> takeIndex(List<int> indexes) => indexes.map((e) => this[e]);
}
class _DistinctComparator<T> {
_DistinctComparator(this.obj, this.equalFn, this.hashCodeFn);
@override
operator ==(Object other) =>
other is _DistinctComparator<T> && equalFn(obj, other.obj);
@override
get hashCode => hashCodeFn(obj);
final T obj;
final bool Function(T, T) equalFn;
final int Function(T) hashCodeFn;
}