Skip to content

Instantly share code, notes, and snippets.

@Kirkkt
Created September 19, 2017 14:59
Show Gist options
  • Save Kirkkt/68b4f65ff35fd94f4a25c95edf3319b0 to your computer and use it in GitHub Desktop.
Save Kirkkt/68b4f65ff35fd94f4a25c95edf3319b0 to your computer and use it in GitHub Desktop.
sg deepClone
/*
Write a function called deepClone which takes an object and creates a copy of it. e.g. {name: "Paddy", address: {town: "Lerum", country: "Sweden"}} -> {name: "Paddy", address: {town: "Lerum", country: "Sweden"}}
*/
const deepClone = entity => {
if (entity === null) {
return null
}
if (entity instanceof Function) {
return entity
}
if (typeof entity !== "object") {
return entity
}
if (entity instanceof Array) {
return entity.map(item => deepClone(item))
}
const result = {}
for (const key in entity) {
result[key] = deepClone(entity[key])
}
return result
}
const run = () => {
const entity = {name: "Paddy", address: {town: "Lerum", country: "Sweden"}}
console.log(JSON.stringify(entity, null, 2))
console.log("--->")
console.log(JSON.stringify(deepClone(entity), null, 2))
}
const test = () => {
const assert = condition => {
if (!condition) {
throw new Error("test failed")
}
console.log("test passed")
}
// this demonstrates the copy is complete, meaning the clone has the exact same set of data
const testCompleteness = () => {
assert(deepClone(null) === null)
assert(deepClone(undefined) === undefined)
assert(deepClone() === undefined)
assert(deepClone(1) === 1)
assert(deepClone("abc") === "abc")
assert(deepClone(() => "abc")() === "abc")
{
const entity = [1, 2, 3]
assert(JSON.stringify(deepClone(entity)) === JSON.stringify(entity))
assert(deepClone(entity)[0] === 1)
assert(deepClone(entity)[1] === 2)
assert(deepClone(entity)[2] === 3)
assert(deepClone(entity).length === 3)
}
{
const entity = { a: 1, b: 2, c: 3 }
assert(JSON.stringify(deepClone(entity)) === JSON.stringify(entity))
assert(deepClone(entity).a === 1)
assert(deepClone(entity).b === 2)
assert(deepClone(entity).c === 3)
assert(Object.keys(deepClone(entity)).length === 3)
}
{
const entity = [{doer: () => "value"}]
assert(deepClone(entity)[0].doer() === "value")
}
}
// this demonstrates it is indeed a separate copy, meaning changing one won't impact the other
const testSeparateCopy = () => {
{
const entity = [1]
const clone = deepClone(entity)
clone[0] = 2
assert(clone[0] === 2)
assert(entity[0] === 1)
}
{
const entity = { a: 1 }
const clone = deepClone(entity)
clone.a = 2
assert(clone.a === 2)
assert(entity.a === 1)
}
}
testCompleteness()
testSeparateCopy()
}
run()
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment