divideList method
Search a list for items that satisfy a test
predicate (matching items),
and then divide that list into parts, such as each part contains one matching item.
Except maybe for the first matching item, it will keep the matching items as
the first item in each part.
Example: Suppose you have a list with Chapters, Texts and Images. You can break it into separate chapters, like this:
bookInfo.divideList((item) => item is Chapter);
In the example below the matching items are 2
and 4
. This means we'll divide
this list into 2 lists, one containing 2
, and another containing 4
.
The 4
will be the first item in its part:
[1,2,3,4,5].divideList((v)=>v==2 || v==4) ➜ [[1,2,3], [4,5]]
Implementation
List<List<T>> divideList(
Predicate<T> test,
) {
if (isEmpty) return [];
final List<List<T>> result = [];
final List<int> indexes = [];
for (int i = 0; i < length; i++) {
if (test(this[i])) indexes.add(i);
}
if (indexes.isEmpty)
return [this];
else {
for (int i = 0; i < indexes.length; i++) {
final ini = (i == 0) ? 0 : indexes[i];
final end = (i == indexes.length - 1) ? (length - 1) : (indexes[i + 1] - 1);
result.add(sublist(ini, end + 1));
}
return result;
}
}