UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

33 lines (31 loc) 806 B
import { is } from "../function/is.js"; import { dfdlT } from "@monstermann/dfdl"; import { markAsMutable } from "@monstermann/remmi"; //#region src/array/flatMap.ts /** * `flatMap(array, mapper)` * * Maps each element in `array` using the `mapper` function and flattens the result by one level. * * ```ts * flatMap([1, 2, 3], (x) => [x, x * 2]); // [1, 2, 2, 4, 3, 6] * ``` * * ```ts * pipe( * [1, 2, 3], * flatMap((x) => [x, x * 2]), * ); // [1, 2, 2, 4, 3, 6] * ``` */ const flatMap = dfdlT((target, mapper) => { let hasChanges = false; const result = target.flatMap((a, b, c) => { const output = mapper(a, b, c); hasChanges ||= !(output.length === 1 && is(output[0], a)); return output; }); return hasChanges ? markAsMutable(result) : target; }, 2); //#endregion export { flatMap };