Skip to content

Instantly share code, notes, and snippets.

@gladimdim
Created January 4, 2022 13:47
Show Gist options
  • Save gladimdim/d171755d268a1e4b96637e4f08c929ef to your computer and use it in GitHub Desktop.
Save gladimdim/d171755d268a1e4b96637e4f08c929ef to your computer and use it in GitHub Desktop.
List Extensions
import 'dart:math';
extension Divide<T> on List<T> {
List<List<T>> divideBy(int number) {
List<T> list = this;
List<List<T>> result = [];
while (list.isNotEmpty) {
result.add([...list.take(number)]);
try {
list = list.sublist(number);
} catch (e) {
break;
}
}
return result;
}
}
typedef ListIntersectionFilter<T, B> = bool Function(T a, B b);
extension Intersection on List {
List<T> intersection<T, B>(
List<B> anotherList, ListIntersectionFilter<T, B> filter) {
List<T> result = [];
for (var element in this) {
for (var anotherElement in anotherList) {
if (filter(element, anotherElement)) {
result.add(element);
}
}
}
return result;
}
List<T> rest<T, B>(List<B> anotherList, ListIntersectionFilter<T, B> filter) {
List<T> result = [];
for (var element in this) {
if (anotherList
.where((anotherElement) => filter(element, anotherElement))
.isEmpty) {
result.add(element);
}
}
return result;
}
}
extension Takers<T> on List<T> {
List<T> takeLast(int number) {
if (number < 0) {
return List<T>.empty(growable: true);
}
if (length <= number) {
return this;
}
return sublist(length - number);
}
T takeRandom() {
int max = length;
Random random = Random();
int next = random.nextInt(max);
return this[next];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment