collect method
Moves the list's elements that satisfy the predicate to consume
.
The elements are passed to consume
in the same order as in the list.
Contract
A ConcurrentModificationError is thrown if consume
modifies the list.
Example
final foo = [1, 2, 3, 4, 5];
final bar = [];
foo.move(where: (e) => e.isEven).collect(bar.add);
print(foo); // [1, 3, 5]
print(bar); // [2, 4]
Implementation
@Possible({ConcurrentModificationError})
void collect(Consume<E> consume) {
final retained = <E>[];
final length = _list.length;
for (final element in _list) {
if (_predicate(element)) {
consume(element);
} else {
retained.add(element);
}
if (length != _list.length) {
throw ConcurrentModificationError(_list);
}
}
if (retained.length != _list.length) {
_list..setRange(0, retained.length, retained)..length = retained.length;
}
}