flat<E> method
Flats each element of this Iterable into zero or more elements.
The resulting Iterable runs through the elements returned
by toElements for each element of this, in iteration order.
The returned Iterable is lazy, and calls toElements for each element
of this iterable every time the returned iterable is iterated.
Example:
var numbers = [[1,2, [7,8]], [3,5]];
print(numbers.flat()); // (1, 2, [7, 8], 3, 5)
print(numbers.flat(depth: 2)); // (1, 2, 7, 8, 3, 5)
Implementation
Iterable<E> flat<E>(
{int? depth, dynamic Function(dynamic e)? toElements}) sync* {
toElements ??= (dynamic e) => e;
depth ??= 1;
for (var element in this) {
if (depth > 0) {
final extracted = toElements(element);
if (extracted is! Iterable) {
yield extracted;
continue;
}
// Use dynamic to handle recursive call type flexibly
yield* extracted.flat<E>(depth: depth - 1, toElements: toElements);
} else {
yield* [toElements(element)];
}
}
}