-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergeObjects.ts
34 lines (30 loc) · 1.07 KB
/
mergeObjects.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import {mergeWith} from 'lodash-es';
export interface MergeObjectMeta {
/**
* `merge` - lodash-es's default, check out lodash-es's `mergeWith` for details.
* `concat` - Joins both arrays, returning a new array.
* `replace` - Replaces the old array with the new array value.
* `retain` - Retains the old array value.
*/
arrayUpdateStrategy: 'merge' | 'concat' | 'replace' | 'retain';
}
export const mergeObjects = <T1 = unknown, T2 = unknown>(
dest: T1,
source: T2,
meta: MergeObjectMeta = {arrayUpdateStrategy: 'replace'}
) => {
const result = mergeWith(dest, source, (objValue, srcValue) => {
if (Array.isArray(objValue) && srcValue) {
if (meta.arrayUpdateStrategy === 'concat') {
return objValue.concat(srcValue);
} else if (meta.arrayUpdateStrategy === 'replace') {
return srcValue;
} else if (meta.arrayUpdateStrategy === 'retain') {
return objValue;
}
// No need to handle the "merge" arrayUpdateStrategy, it happens by
// default if nothing is returned
}
});
return result as T1 & T2;
};