Last active
May 8, 2019 16:17
-
-
Save splincode/81a44f2adb287b13491d8e1794400bf5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 deepCopy(obj) { | |
return JSON.parse(JSON.stringify(obj)); // serialize -> deserialize -> unique clone | |
} | |
function copy(obj) { | |
let clone = Array.isArray(obj) ? [] : {}; | |
for (let key in obj) { | |
let value = obj[key]; | |
clone[key] = (typeof value === "object") ? copy(value) : value; | |
} | |
return clone; | |
} | |
const original = { | |
a: new Date(), | |
b: NaN, | |
c: new Function(), | |
d: undefined, | |
e: function(){}, | |
f: Number, | |
g: false, | |
h: Infinity | |
} | |
const firstCopy = deepCopy(original); | |
// JSON-safe { a: "2019-04-30T19:18:47.026Z", b: null, g: false, h: null } | |
const secondCopy = copy(original); | |
// { a: {}, b: NaN, c: ƒ( ), d: undefined, e: ƒ (), f: Number(), g: false, h: Infinity } | |
// But we see that complex structures (Date) we still could not correct copy | |
// original | |
const animals = { | |
zebra: { | |
food: ['leaves', 'bark'], | |
name: 'zebra' | |
}, | |
panda: { | |
food: [], | |
name: 'panda' | |
} | |
}; | |
const newAnimals = copy(animals); // deep clone | |
newAnimals.panda.food.push('leaves'); | |
console.log(animals.panda.food); // [ ] | |
console.log(newAnimals.panda.food); // [ 'leaves' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment