groupConsecutiveElementsWhile<T> function
Returns a new array by putting consecutive elements satisfying predicate into a new
array and returning others as they are.
Ex: 1, "ha", 3, "ha", "ha"
=> [1, "ha", 3, "ha", "ha"
]
where predicate: (v, vprev) => typeof v === typeof vPrev
Implementation
List groupConsecutiveElementsWhile<T>(
List<T> arr, bool Function(T currElm, T prevElm) predicate) {
var groups = [];
dynamic currElm;
List currGroup;
for (var i = 0; i < arr.length; i++) {
currElm = arr[i];
if (i > 0 && predicate(currElm, arr[i - 1])) {
currGroup = groups[groups.length - 1];
currGroup.add(currElm);
} else {
groups.add([currElm]);
}
}
return groups.map((g) => (g.length == 1 ? g[0] : g)).toList();
}