Skip to content

Instantly share code, notes, and snippets.

@fwon
Created March 30, 2017 07:50
Show Gist options
  • Save fwon/4b8b5c2061978d0029c5be291541593f to your computer and use it in GitHub Desktop.
Save fwon/4b8b5c2061978d0029c5be291541593f to your computer and use it in GitHub Desktop.
deep clone
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