Some usefull list helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///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