-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
index.js
49 lines (42 loc) · 1.06 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
'use strict';
/**
* Module dependenices
*/
const clone = require('shallow-clone');
const typeOf = require('kind-of');
const { isPlainObject } = require('is-plain-object');
function cloneDeep(val, instanceClone) {
switch (typeOf(val)) {
case 'object':
return cloneObjectDeep(val, instanceClone);
case 'array':
return cloneArrayDeep(val, instanceClone);
default: {
return clone(val);
}
}
}
function cloneObjectDeep(val, instanceClone) {
if (typeof instanceClone === 'function') {
return instanceClone(val);
}
if (instanceClone || isPlainObject(val)) {
const res = (val.constructor !== undefined) ? new val.constructor() : Object.create(null);
for (let key in val) {
res[key] = cloneDeep(val[key], instanceClone);
}
return res;
}
return val;
}
function cloneArrayDeep(val, instanceClone) {
const res = new val.constructor(val.length);
for (let i = 0; i < val.length; i++) {
res[i] = cloneDeep(val[i], instanceClone);
}
return res;
}
/**
* Expose `cloneDeep`
*/
module.exports = cloneDeep;