You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
852 B
39 lines
852 B
function deepCopy(obj, parent = null) { |
|
let result |
|
let _parent = parent |
|
while (_parent) { |
|
if (_parent.originalParent === obj) { |
|
return _parent.currentParent |
|
} |
|
_parent = _parent.parent |
|
} |
|
if (obj && typeof(obj) === 'object') { |
|
if (obj instanceof RegExp) { |
|
result = new RegExp(obj.source, obj.flags) |
|
} else if (obj instanceof Date) { |
|
result = new Date(obj.getTime()) |
|
} else { |
|
if (obj instanceof Array) { |
|
result = [] |
|
} else { |
|
let proto = Object.getPrototypeOf(obj) |
|
result = Object.create(proto) |
|
} |
|
for (let i in obj) { |
|
if (obj[i] && typeof(obj[i]) === 'object') { |
|
result[i] = deepCopy(obj[i], { |
|
originalParent: obj, |
|
currentParent: result, |
|
parent: parent |
|
}) |
|
} else { |
|
result[i] = obj[i] |
|
} |
|
} |
|
} |
|
} else { |
|
return obj |
|
} |
|
return result |
|
} |
|
export default deepCopy |