UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

41 lines (39 loc) 989 B
import { is } from "../function/is.js"; import { dfdlT } from "@monstermann/dfdl"; import { cloneArray } from "@monstermann/remmi"; //#region src/array/findMap.ts /** * `findMap(array, predicate, mapper)` * * Finds the first element in `array` that satisfies the provided `predicate` function and applies the `mapper` function to it, returning a new array with the mapped element. * * ```ts * findMap( * [1, 2, 3, 4], * (x) => x > 2, * (x) => x * 10, * ); // [1, 2, 30, 4] * ``` * * ```ts * pipe( * [1, 2, 3, 4], * findMap( * (x) => x > 2, * (x) => x * 10, * ), * ); // [1, 2, 30, 4] * ``` */ const findMap = dfdlT((target, predicate, mapper) => { const idx = target.findIndex(predicate); if (idx === -1) return target; const prev = target[idx]; const next = mapper(prev, idx, target); if (is(prev, next)) return target; const result = cloneArray(target); result.splice(idx, 1, next); return result; }, 3); //#endregion export { findMap };