-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
extend.js
106 lines (92 loc) · 2.85 KB
/
extend.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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
'use strict';
/*!
* node.extend
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* @fileoverview
* Port of jQuery.extend that actually works on node.js
*/
var is = require('is');
var has = require('has');
var defineProperty = Object.defineProperty;
var gOPD = Object.getOwnPropertyDescriptor;
// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
var setProperty = function setP(target, name, value) {
if (defineProperty && name === '__proto__') {
defineProperty(target, name, {
enumerable: true,
configurable: true,
value: value,
writable: true
});
} else {
target[name] = value; // eslint-disable-line no-param-reassign
}
};
// Return undefined instead of __proto__ if '__proto__' is not an own property
var getProperty = function getP(obj, name) {
if (name === '__proto__') {
if (!has(obj, name)) {
return void 0;
} else if (gOPD) {
// In early versions of node, obj['__proto__'] is buggy when obj has
// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
return gOPD(obj, name).value;
}
}
return obj[name];
};
module.exports = function extend() {
var target = arguments[0] || {};
var i = 1;
var length = arguments.length;
var deep = false;
var options, name, src, copy, copyIsArray, clone;
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== 'object' && !is.fn(target)) {
target = {};
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
options = arguments[i];
if (options != null) {
if (typeof options === 'string') {
options = options.split('');
}
// Extend the base object
for (name in options) {
src = getProperty(target, name);
copy = getProperty(options, name);
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && (is.hash(copy) || (copyIsArray = is.array(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && is.array(src) ? src : [];
} else {
clone = src && is.hash(src) ? src : {};
}
// Never move original objects, clone them
setProperty(target, name, extend(deep, clone, copy));
// Don't bring in undefined values
} else if (typeof copy !== 'undefined') {
setProperty(target, name, copy);
}
}
}
}
// Return the modified object
return target;
};