Created
March 30, 2017 07:50
-
-
Save fwon/4b8b5c2061978d0029c5be291541593f to your computer and use it in GitHub Desktop.
deep clone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deepClone(obj, hash = new Map()) { | |
if (Object(obj) !== obj) return obj; // primitives | |
if (hash.has(obj)) return hash.get(obj); // cyclic reference | |
var result = Array.isArray(obj) ? [] | |
: obj.constructor ? new obj.constructor() : {}; | |
hash.set(obj, result); | |
if (obj instanceof Map) | |
Array.from(obj, ([key, val]) => result.set(key, deepClone(val, hash)) ); | |
return Object.assign(result, ...Object.keys(obj).map ( | |
key => ({ [key]: deepClone(obj[key], hash) }) )); | |
} | |
// sample data | |
function A() {} | |
function B() {} | |
var a = new A(); | |
var b = new B(); | |
a.b = b; | |
b.a = a; | |
// test it | |
var c = deepClone(a); | |
console.log('a' in c.b.a.b); // true | |
Source |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment