@monstermann/fn
Version:
A utility library for TypeScript.
35 lines (33 loc) • 933 B
JavaScript
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/removeLastOrElse.ts
/**
* `removeLastOrElse(target, value, orElse)`
*
* Removes the last occurrence of `value` from `target` array. If the value is not found, calls the `orElse` function with the original array and returns its result.
*
* ```ts
* removeLastOrElse([1, 2, 3, 2], 2, () => []); // [1, 2, 3]
* removeLastOrElse([1, 2, 3], 4, (arr) => arr); // [1, 2, 3]
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 2],
* removeLastOrElse(2, () => []),
* ); // [1, 2, 3]
* pipe(
* [1, 2, 3],
* removeLastOrElse(4, (arr) => arr),
* ); // [1, 2, 3]
* ```
*/
const removeLastOrElse = dfdlT((target, value, orElse) => {
const idx = target.lastIndexOf(value);
if (idx < 0) return orElse(target);
const result = cloneArray(target);
result.splice(idx, 1);
return result;
}, 3);
//#endregion
export { removeLastOrElse };