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