Skip to content

flatMap() function

返回通过运行每个元素并展平映射结果得到的展平后的 Iterable/AsyncIterable。

Signature:

typescript
declare function flatMap<A, B = unknown>(
  f: (a: A) => B,
  iterable: Iterable<A>,
): IterableIterator<DeepFlatSync<B, 1>>;

Example

ts
const iter = flatMap((s) => s.split(" "), ["It is", "a good", "day"]);
iter.next(); // {done:false, value: "It"}
iter.next(); // {done:false, value: "is"}
iter.next(); // {done:false, value: "a"}
iter.next(); // {done:false, value: "good"},
iter.next(); // {done:false, value: "day"},
iter.next(); // {done:true, value: undefined}

// with pipe
pipe(
  ["It is", "a good", "day"],
  flatMap((s) => s.split(" ")),
  toArray,
); // ["It", "is", "a", "good", "day"]

await pipe(
  Promise.resolve(["It is", "a good", "day"]),
  flatMap((s) => s.split(" ")),
  toArray,
); // ["It", "is", "a", "good", "day"]

// if you want to use asynchronous callback
await pipe(
  Promise.resolve(["It is", "a good", "day"]),
  toAsync,
  flatMap(async (s) => s.split(" ")),
  toArray,
); // ["It", "is", "a", "good", "day"]

Try It

see pipe, toAsync, toArray

Open Source Code

Released under the Apache-2.0 License.