-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
90 lines (81 loc) · 2.62 KB
/
index.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { isObject, isArray, isRegExp, isString } from 'is-all-utils';
interface Options {
removedKeys?: any[];
removedValues?: any[];
excludedKeys?: any[];
excludedValues?: any[];
[key: string]: any;
}
/**
* @author Yoni Calsin <helloyonicb@gmail.com>
* @documentation https://github.com/yonicalsin/merge-all-objects
*/
const Merge = <T extends Options = Options>(...objs: (T | Options)[]): T => {
let payload: Options = {},
source: Options,
key: string | number;
let lastObj: any = objs[objs.length - 1] as any;
// For add the excluded keys
let {
// For remove
removedKeys = lastObj?.removedKeys || [],
removedValues = lastObj?.removedValues || [],
// For excluded
excludedKeys = lastObj?.excludedKeys || [],
excludedValues = lastObj?.excludedValues || [],
} = lastObj || {};
if (isArray(lastObj)) {
excludedKeys = lastObj;
delete objs[objs.length - 1];
} else {
if (
lastObj?.removedKeys ||
lastObj?.removedValues ||
lastObj?.excludedKeys ||
lastObj?.excludedValues
) {
delete objs[objs.length - 1];
}
}
while (objs.length > 0) {
source = objs.splice(0, 1)[0];
if (isObject(source)) {
for (key in source) {
if (source.hasOwnProperty(key)) {
const value = source[key];
// Array.includes validation function including custom regular expressions
const is = (arr: any[], index) => {
if (arr.length > 0) {
return arr.some(exclude => {
if (isRegExp(exclude) && isString(index)) {
return (exclude as RegExp).test(index as string);
}
return index === exclude;
});
}
return false;
};
if (is(removedValues, value) || is(removedKeys, key)) {
// empty
} else if (is(excludedValues, value) || is(excludedKeys, key)) {
payload[key] = value;
} else {
if (isObject(value)) {
payload[key] = Merge(payload[key], value, {
removedKeys,
removedValues,
excludedKeys,
excludedValues,
});
} else {
payload[key] = value;
}
}
}
}
}
}
return payload as T;
};
export { Merge };
export default Merge;