@monstermann/fn
Version:
A utility library for TypeScript.
43 lines (41 loc) • 1.05 kB
JavaScript
import { is } from "../function/is.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/findMapOr.ts
/**
* `findMapOr(array, predicate, mapper, fallback)`
*
* 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, or `fallback` if no element is found.
*
* ```ts
* findMapOr(
* [1, 2, 3, 4],
* (x) => x > 10,
* (x) => x * 10,
* [],
* ); // []
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 4],
* findMapOr(
* (x) => x > 10,
* (x) => x * 10,
* [],
* ),
* ); // []
* ```
*/
const findMapOr = dfdlT((target, predicate, mapper, or) => {
const idx = target.findIndex(predicate);
if (idx === -1) return or;
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;
}, 4);
//#endregion
export { findMapOr };