-
Notifications
You must be signed in to change notification settings - Fork 0
/
assign.js
42 lines (39 loc) · 1.23 KB
/
assign.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
'use strict';
function assign(target) {
const sources = Array.prototype.slice.call(arguments, 1);
sources.forEach((source) => {
Object.keys(source).forEach((key) => {
// If the target key has an object
if (key in target && target[key] instanceof Object) {
// and the source key is also an object
if (source[key] instanceof Object) {
// then merge them (source overwrites same keys).
return assign(target[key], source[key]);
}
}
target[key] = source[key];
});
});
return target;
}
function merge(target) {
const sources = Array.prototype.slice.call(arguments, 1);
sources.forEach((source) => {
Object.keys(source).forEach((key) => {
// If the target key has an object
if (key in target && target[key] instanceof Object) {
// and the source key is also an object
if (source[key] instanceof Object) {
// then merge them (source overwrites same keys).
return merge(target[key], source[key]);
}
// If the source key is not an object, we don't overwrite the target object.
return;
}
target[key] = source[key];
});
});
return target;
}
module.exports = assign;
assign.merge = merge;