Skip to content

beforeAndAfter

beforeAndAfter<T>(iterable, predicate): [IterableIterator<T, any, any>, IterableIterator<T, any, any>]

Defined in: packages/core/src/iterable/before-and-after.ts:25

Splits an iterable at the first element failing predicate, returning the prefix and the remainder as two iterators over the same source.

The other case takeWhile gets wrong: it discards everything from the split point on. Here the failing element starts the second iterator, so nothing is lost and the source is still only walked once.

The two share one underlying iterator, so the first must be consumed before the second. Reading the second early is allowed and drains the first silently, discarding its elements — that is the only way to know where the split is. Abandoning the first part-way is also allowed: the second then resumes from wherever the source was left, with no boundary element.

Time complexity: O(1) per element. Memory: O(1) — one element is held at the boundary, never the prefix.

T

Iterable<T>

The input iterable.

Predicate<[T, number]>

Receives each element and its zero-based index.

[IterableIterator<T, any, any>, IterableIterator<T, any, any>]

The leading elements that satisfy predicate, then the rest starting at the first that does not.