Skip to content

peek() function

入力リストを反復処理し、Iterable/AsyncIterable の各要素に対して提供されたfを呼び出します。pipe内で副作用を作成したい場合に使用します。

Signature:

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

Example

ts
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

Open Source Code

Released under the Apache-2.0 License.