-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
96 lines (74 loc) · 2.31 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
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
/**
* Created by alykoshin on 22.01.16.
*/
'use strict';
/**
* Node 0.10-0.12 does not supports Object.assign()
*
* Source below is based upon
* https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
*/
/**
* @param {object} target - target object
* @param {object} source - source object
* @returns {object}
*/
var _assign = function(target, source) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
var s = source[nextKey];
if (
typeof s === 'undefined' ||
typeof s === 'boolean' ||
typeof s === 'number' ||
typeof s === 'string' ||
s === null
) {
target[nextKey] = s;
} else if (s instanceof Date) {
target[nextKey] = new Date(s.getTime());
} else if (s instanceof RegExp) {
target[nextKey] = new RegExp(s);
} else if (Array.isArray(s)) {
var arr = s.slice();
var i = arr.length;
while (i--){
arr[i] = _assign(arr[i], s[i]);
}
target[nextKey] = arr;
} else if (typeof s === 'object') {
if (typeof target[nextKey] !== 'object') { // If target has no such key or it is non-object
target[nextKey] = {}; // Replace it with empty object
}
//for (var nextKey in source) {
// if (source.hasOwnProperty(nextKey)) {
//var s = source[ nextKey ];
_assign(target[ nextKey ], source[ nextKey ]);
//}
//}
} else { // unknown type....
throw new Error('Assignment error: source: \''+JSON.stringify(s)+', typeof source: \''+(typeof source)+'\'');
}
}
}
return target;
};
/** @param {object} target - target object, followed by list of source objects
* @returns {object}
*/
var assign = function (target /* sources */) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
//var output = Object(target);
var output = { value: target };
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
var input = { value: source };
output = _assign(output, input);
}
}
return output.value;
};
module.exports = assign;