Last active
December 19, 2017 15:43
-
-
Save black-black-cat/6933f20391fac62252f788670d25269a to your computer and use it in GitHub Desktop.
clone vs deep clone
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 clone(value) { | |
var result | |
if (Array.isArray(value)) { | |
result = [] | |
value.forEach(function (item) { | |
result[result.length] = item | |
}) | |
} else if (typeof value === 'object') { | |
result = {} | |
Object.keys(value).forEach(function (key) { | |
result[key] = value[key] | |
}) | |
} else { | |
result = value | |
} | |
return result | |
} | |
module.exports = clone |
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 cloneDeep(value) { | |
var result | |
if (Array.isArray(value)) { | |
result = [] | |
value.forEach(function (item) { | |
result[result.length] = cloneDeep(item) | |
}) | |
} else if (typeof value === 'object') { | |
result = {} | |
Object.keys(value).forEach(function (key) { | |
result[key] = cloneDeep(value[key]) | |
}) | |
} else { | |
result = value | |
} | |
return result | |
} | |
module.exports = cloneDeep |
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
let cloneDeep = require('./cloneDeep') | |
let clone = require('./clone') | |
let foo = { | |
a: { | |
a: 1, | |
b: { | |
c: [1,2] | |
} | |
} | |
} | |
let bar = cloneDeep(foo) | |
let eoo = clone(foo) | |
const dir = (arg) => console.dir(arg, {depth: Infinity}) | |
dir(bar) | |
dir(foo) | |
console.log(bar != foo) | |
console.log(bar.a.b != foo.a.b) | |
console.log(bar.a.b.c != foo.a.b.c) | |
console.log(eoo != foo) | |
console.log(eoo.a.b == foo.a.b) | |
console.log(eoo.a.b.c == foo.a.b.c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment