Skip to content

Instantly share code, notes, and snippets.

@stijn1989
Last active August 24, 2022 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stijn1989/04b33b146a3048c04d036a28d8fabca5 to your computer and use it in GitHub Desktop.
Save stijn1989/04b33b146a3048c04d036a28d8fabca5 to your computer and use it in GitHub Desktop.
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