-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
49 lines (44 loc) · 1.21 KB
/
index.js
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
"use strict";
const XAssign = {
assign: function (...args) {
/**
* Combine object properties or concat array properties
*
* @param {any} acc the target or accumulator
* @param {any} obj object to apply
*/
function apply(acc, obj) {
if (obj == null || typeof obj !== "object") {
return; // ignore non-object args
}
Object.keys(obj).forEach((key) => {
const value = obj[key];
if (Array.isArray(value)) {
acc[key] =
acc[key] && Array.isArray(acc[key])
? acc[key].concat(value)
: value;
} else if (typeof value === "object") {
acc[key] = acc[key] || {};
if (Array.isArray(acc[key])) {
acc[key] = {}; // getting overridden with an Object!
apply(acc[key], value);
} else if (typeof acc[key] === "object") {
apply(acc[key], value);
} else {
acc[key] = value;
}
} else {
acc[key] = value;
}
});
}
/**
* Apply merge for each object argument.
*/
const result = {};
args.forEach((obj) => apply(result, obj));
return result;
},
};
module.exports = XAssign;