@monstermann/fn
Version:
A utility library for TypeScript.
29 lines (27 loc) • 758 B
JavaScript
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/removeLastOr.ts
/**
* `removeLastOr(target, value, or)`
*
* Removes the last occurrence of `value` from `target` array. If the value is not found, returns the fallback value `or`.
*
* ```ts
* removeLastOr([1, 2, 3, 2], 2, []); // [1, 2, 3]
* removeLastOr([1, 2, 3], 4, []); // []
* ```
*
* ```ts
* pipe([1, 2, 3, 2], removeLastOr(2, [])); // [1, 2, 3]
* pipe([1, 2, 3], removeLastOr(4, [])); // []
* ```
*/
const removeLastOr = dfdlT((target, value, or) => {
const idx = target.lastIndexOf(value);
if (idx < 0) return or;
const result = cloneArray(target);
result.splice(idx, 1);
return result;
}, 3);
//#endregion
export { removeLastOr };