Repository navigation
Expand file tree
/
Copy pathdeepCopy.js
More file actions
67 lines (56 loc) · 1.48 KB
/
Copy pathdeepCopy.js
File metadata and controls
67 lines (56 loc) · 1.48 KB
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
var utils = {
// 数据类型检测
toType: val =>
Object.prototype.toString.call(val).slice(8, -1).toLocaleLowerCase(),
isFun(func) {
return typeof func.__proto__ === 'function' && typeof func === 'function';
},
each(itor, cb) {
if (typeof cb !== 'function') return;
if (Array.isArray(itor)) {
itor.forEach(cb);
} else if (typeof itor === 'object' && itor) {
for (var key in itor) {
cb(itor[key], key);
}
}
}
};
var copy = function () {
const { toType, isFun, each } = utils;
var target = arguments[0],
map = arguments[arguments.length - 1],
deep,
clone;
map instanceof Map || (map = new Map());
if (toType(target) === 'boolean') {
deep = target;
target = arguments[1];
}
if (map.has(target)) {
return deep ? null : target;
}
// 处理原始值,例如 number,string,boolean,symbol,bigint,null,undefined
if (
/^number|string|boolean|symbol|bigint$/i.test(toType(target)) ||
target == null
) {
return target;
}
// 内置类对象
if (/^regexp|date$/gim.test(toType(target)))
return new target.constructor(target);
// 处理函数
if (isFun(target)) {
return function () {
return target.apply(this, [].slice.call(arguments));
};
}
clone = Array.isArray(target) ? [] : {};
each(target, function (item, key) {
deep && map.set(item, true);
clone[key] = deep ? copy(deep, item, map) : item;
});
return clone;
};
module.exports = copy;