Skip to main content

peek

peek() function

Iterate over an input list, calling a provided f for each element in the Iterable/AsyncIterable. Use it when you want to create an effect inside pipe.

Signature:
declare function peek<T>(f: (a: T) => unknown, iterable: Iterable<T>): IterableIterator<T>;

declare function peek<T>(f: (a: T) => unknown, iterable: AsyncIterable<T>): AsyncIterableIterator<T>;

declare function peek<T extends Iterable<unknown> | AsyncIterable<unknown>>(f: (a: Awaited<IterableInfer<T>>) => unknown): (iterable: T) => ReturnIterableIteratorType<T>;

Example

const iter = peek(a => console.log(a), [1, 2, 3, 4]);
iter.next() // {done:false, value: 1} // log 1
iter.next() // {done:false, value: 2} // log 2
iter.next() // {done:false, value: 3} // log 3
iter.next() // {done:false, value: 4} // log 4

// with pipe
pipe(
[1, 2, 3, 4],
peek(a => console.log(a)),
toArray,
); // [1, 2, 3, 4] // log 1,2,3,4

await pipe(
Promise.resolve([1, 2, 3, 4]),
peek(a => console.log(a)),
toArray,
); // [1, 2, 3, 4] // log 1,2,3,4

// if you want to use asynchronous callback
await pipe(
Promise.resolve([1, 2, 3, 4]),
toAsync,
peek(async (a) => console.log(a)),
toArray,
); // [1, 2, 3, 4] // log 1,2,3,4

// with toAsync
await pipe(
[Promise.resolve(1), Promise.resolve(2), Promise.resolve(3), Promise.resolve(4)],
toAsync,
peek(a => console.log(a)),
toArray,
); // [1, 2, 3, 4] // log 1,2,3,4

Try It

see pipe, toAsync, toArray