@monstermann/fn
Version:
A utility library for TypeScript.
29 lines (27 loc) • 829 B
JavaScript
import { is } from "../function/is.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/replace.ts
/**
* `replace(target, value, replacement)`
*
* Replaces the first occurrence of `value` with `replacement` in `target` array. If the value is not found or if value and replacement are the same, returns the original array unchanged.
*
* ```ts
* replace([1, 2, 3, 2], 2, 5); // [1, 5, 3, 2]
* ```
*
* ```ts
* pipe([1, 2, 3, 2], replace(2, 5)); // [1, 5, 3, 2]
* ```
*/
const replace = dfdlT((target, value, replacement) => {
if (is(value, replacement)) return target;
const idx = target.indexOf(value);
if (idx === -1) return target;
const result = cloneArray(target);
result.splice(idx, 1, replacement);
return result;
}, 3);
//#endregion
export { replace };