UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

42 lines (40 loc) 993 B
import { dfdlT } from "@monstermann/dfdl"; import { cloneArray } from "@monstermann/remmi"; //#region src/array/findMapAll.ts /** * `findMapAll(array, predicate, mapper)` * * Finds all elements in `array` that satisfy the provided `predicate` function and applies the `mapper` function to each of them, returning a new array with the mapped elements. * * ```ts * findMapAll( * [1, 2, 3, 4], * (x) => x > 2, * (x) => x * 10, * ); // [1, 2, 30, 40] * ``` * * ```ts * pipe( * [1, 2, 3, 4], * findMapAll( * (x) => x > 2, * (x) => x * 10, * ), * ); // [1, 2, 30, 40] * ``` */ const findMapAll = dfdlT((target, predicate, mapper) => { let result; for (let i = 0; i < target.length; i++) { const prev = target[i]; if (!predicate(prev, i, target)) continue; const next = mapper(prev, i, target); if (prev === next) continue; result ??= cloneArray(target); result[i] = next; } return result ?? target; }, 3); //#endregion export { findMapAll };