Skip to main content

scan

scan() function

Returns a Iterable/AsyncIterable of successively reduced values from the left. It's similar to reduce

Signature:
declare function scan<A>(f: (a: A, b: A) => A, iterable: Iterable<A>): IterableIterator<A>;

declare function scan<A extends readonly []>(f: Arrow, iterable: A): IterableIterator<never>;

declare function scan<A, B>(f: (a: B, b: A) => B, iterable: Iterable<A>): IterableIterator<B>;

declare function scan<A extends readonly [], B>(f: Arrow, seed: B, iterable: A): IterableIterator<B>;

declare function scan<A, B>(f: (a: B, b: A) => B, seed: B, iterable: Iterable<A>): IterableIterator<B>;

declare function scan<A>(f: (a: A, b: A) => A | Promise<A>, iterable: AsyncIterable<A>): AsyncIterableIterator<A>;

declare function scan<A, B>(f: (a: Awaited<B>, b: A) => B | Promise<B>, iterable: AsyncIterable<A>): AsyncIterableIterator<Awaited<B>>;

declare function scan<A, B>(f: (a: Awaited<B>, b: A) => B | Promise<B>, seed: B | Promise<B>, iterable: AsyncIterable<A>): AsyncIterableIterator<B>;

declare function scan<A extends Iterable<unknown> | AsyncIterable<unknown>, B>(f: (a: B, b: IterableInfer<A>) => B | Promise<B>): (iterable: A) => ReturnIterableIteratorType<A, B>;

declare function scan<A extends Iterable<unknown> | AsyncIterable<unknown>>(f: (a: IterableInfer<A>, b: IterableInfer<A>) => IterableInfer<A> | Promise<IterableInfer<A>>): (iterable: A) => ReturnIterableIteratorType<A, IterableInfer<A>>;

Example

const iter = scan((acc, cur) => acc * cur, 1, [1, 2, 3, 4 ]);
iter.next(); // {value: 1, done:false}
iter.next(); // {value: 1, done:false}
iter.next(); // {value: 2, done:false}
iter.next(); // {value: 6, done:false}
iter.next(); // {value: 24, done:false}
iter.next(); // {value: undefined, done: true}

// with pipe
pipe(
[1, 2, 3, 4],
scan((acc, cur) => acc * cur),
toArray,
); // [1, 2, 6, 24]

Open Source Code