-
Notifications
You must be signed in to change notification settings - Fork 75
/
defaults.js
48 lines (44 loc) · 1.21 KB
/
defaults.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
/**
* @module 101/defaults
*/
var isObject = require('./is-object');
var isBoolean = require('./is-boolean');
var exists = require('./exists');
/**
* Mixes in properties from source into target when
* the property is not a property of `target`
* @param {Object} [target] Mix into
* @param {Object} source The defaults description
* @return {Object} THe resulting target
*/
module.exports = defaults;
function defaults (target, source, deep) {
if (arguments.length === 1) {
source = target;
return function (target) {
return defaults(target, source);
};
} else if (isBoolean(source)) {
deep = source;
source = target;
return function (target) {
return defaults(target, source, deep);
};
}
target = target || {};
deep = deep || false;
if (!source) {
return target;
}
return reduceObject(target, source, deep);
}
function reduceObject (target, source, deep) {
return Object.keys(source).reduce(function (target, key) {
if (isObject(target[key]) && isObject(source[key]) && deep) {
reduceObject(target[key], source[key]);
return target;
}
target[key] = exists(target[key]) ? target[key] : source[key];
return target;
}, target);
}