Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some usefull list helpers
///This extension contains some usefull helpers for lists.
extension ListHelpers<E> on List<E>
{
///Calculates the sum of the list items.
///
/// [callBackValue] returns the number value of the item that is added
/// to the sum.
int sum(int Function(E item) callbackValue)
{
int sum = 0;
for(var item in this) {
sum += callbackValue(item);
}
return sum;
}
///Make a new list that contains unique combinations of the list items.
///
/// If this list contains the items [1,2].
/// It will return the following combinations:
/// [
/// [],
/// [1],
/// [2],
/// [2, 1]
/// ]
///
/// If [removeEmptyRoot] is set to false, the first element of the returned
/// list contains an empty list. By default, this is set to true.
List<List<E>> powerSet({bool removeEmptyRoot = true})
{
List<List<E>> combinations = [[]];
for(var item in this) {
for(var combination in combinations) {
combinations.add([item, ...combination]);
}
}
if(removeEmptyRoot) {
combinations = combinations.sublist(1);
}
return combinations;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment