Merge branch 'mapIf'

This commit is contained in:
Yanick Champoux 2024-02-27 12:15:47 -05:00
commit aeb46565a9
4 changed files with 80 additions and 5 deletions

View File

@ -0,0 +1,5 @@
---
"@yanick/updeep-remeda": minor
---
add functions mapIf and mapIfElse

View File

@ -1,4 +1,3 @@
# API
<div class="info">
@ -27,8 +26,8 @@ Or you can import the functions piecemeal:
import { updateIn, omit } from '@yanick/updeep-remeda';
```
## `u(dataIn, updates)`
## `u.update(dataIn, updates)`
Update as many values as you want, as deeply as you want. The `updates` parameter can either be an object, a function, or a value. Everything returned from `u` is frozen recursively.
@ -294,6 +293,18 @@ Essentially the same as their Remeda counterparts. The difference being
that if the transformation results in no change, the original object/array is
returned.
## `u.map(objectIn, updates)`
Applies the updates on all entries of `objectIn`.
## `u.mapIf(objectIn, predicate, updates)`
Shorthand for `u.map( objectIn, u.if(predicate,updates) )`.
## `u.mapIfElse(objectIn, predicate, updates, updatesElse)`
Shorthand for `u.map( objectIn, u.ifElse(predicate,updates,updatesElse) )`.
## `u.matches(dataIn, condition)`
Do a deep comparison with `condition`, and returns

23
src/mapIf.test.ts Normal file
View File

@ -0,0 +1,23 @@
import { expect, test, describe } from "vitest";
import mapIf, { mapIfElse } from "./mapIf.js";
test("does updates with the if and else", () => {
const object = [
{ x: 1, y: 0 },
{ x: 2, y: 0 },
{ x: 3, y: 0 },
];
expect(mapIfElse(object, { x: 2 }, { y: 2 }, { y: 3 })).toEqual([
{ x: 1, y: 3 },
{ x: 2, y: 2 },
{ x: 3, y: 3 },
]);
expect(mapIf(object, { x: 2 }, { y: 2 })).toEqual([
{ x: 1, y: 0 },
{ x: 2, y: 2 },
{ x: 3, y: 0 },
]);
});

36
src/mapIf.ts Normal file
View File

@ -0,0 +1,36 @@
import wrap from "./wrap.js";
import matches from "./matches.js";
import map from "./map.js";
import ifElse from "./ifElse.js";
function _mapIfElse(object, predicate, trueUpdates, falseUpdates) {
const test =
typeof predicate === "function"
? predicate
: typeof predicate === "object"
? matches(predicate)
: predicate;
const updates = test ? trueUpdates : falseUpdates;
return map(object, ifElse(test, trueUpdates, falseUpdates));
}
function mapIf(object, predicate, trueUpdates) {
return _mapIfElse(object, predicate, trueUpdates, (x) => x);
}
type Predicate = ((source: any) => boolean) | boolean | Record<string, any>;
export interface MapIfElse {
(object, predicate: Predicate, trueUpdates, falseUpdates): unknown;
(predicate: Predicate, trueUpdates, falseUpdates): (unknown) => unknown;
}
export interface MapIf {
(object, predicate: Predicate, trueUpdates): unknown;
(predicate: Predicate, trueUpdates): (unknown) => unknown;
}
export default wrap(mapIf) as MapIf;
export const mapIfElse = _mapIfElse as any as MapIfElse;