@monstermann/fn
Version:
A utility library for TypeScript.
33 lines (31 loc) • 919 B
JavaScript
import { is } from "../function/is.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/findReplace.ts
/**
* `findReplace(array, predicate, replacement)`
*
* Finds the first element in `array` that satisfies the provided `predicate` function and replaces it with `replacement`, returning a new array with the replaced element.
*
* ```ts
* findReplace([1, 2, 3, 4], (x) => x > 2, 10); // [1, 2, 10, 4]
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 4],
* findReplace((x) => x > 2, 10),
* ); // [1, 2, 10, 4]
* ```
*/
const findReplace = dfdlT((target, predicate, replacement) => {
const idx = target.findIndex(predicate);
if (idx === -1) return target;
const prev = target[idx];
if (is(prev, replacement)) return target;
const result = cloneArray(target);
result.splice(idx, 1, replacement);
return result;
}, 3);
//#endregion
export { findReplace };