intersperseWith<B> method
Iterable<B>
intersperseWith<B>({
- required Transformer<
A, B> itemBuilder, - required SeparatorBuilder<
A, B> separatorBuilder, - Transformer<
A, B> ? beforeFirst, - Transformer<
A, B> ? afterLast,
Creates a new Iterable with the separator interposed between elements.
Each element in the new iterable is built from the element in the original
iterable using itemBuilder
.
Each separator in the new iterable is built using separatorBuilder
that
accepts the original item before and after this separator.
If beforeFirst
is not null and the iterable is not empty, beforeFirst
is used as a separator builder that accepts the first element. The result
of its call is prepended to the iterable.
If afterLast
is not null and the iterable is not empty, afterLast
is
used as a separator builder that accepts the last element. The result of
its call is appended to the iterable.
Implementation
Iterable<B> intersperseWith<B>({
required Transformer<A, B> itemBuilder,
required SeparatorBuilder<A, B> separatorBuilder,
Transformer<A, B>? beforeFirst,
Transformer<A, B>? afterLast,
}) sync* {
final iterator = this.iterator;
if (iterator.moveNext()) {
if (beforeFirst != null) {
yield beforeFirst(iterator.current);
}
yield itemBuilder(iterator.current);
var prev = iterator.current;
while (iterator.moveNext()) {
yield separatorBuilder(prev, iterator.current);
prev = iterator.current;
yield itemBuilder(iterator.current);
}
if (afterLast != null) {
yield afterLast(prev);
}
}
}