Skip to content

Instantly share code, notes, and snippets.

@RichardMarks
Created June 2, 2017 19:46
Show Gist options
  • Save RichardMarks/76aceb2753d842df76e82fb3f65d6c8b to your computer and use it in GitHub Desktop.
Save RichardMarks/76aceb2753d842df76e82fb3f65d6c8b to your computer and use it in GitHub Desktop.
JavaScript ES6 - simple deep copy routine (does not handle circular references) MIT License
// deepCopy.js
// simple deep copy routine
// does not handle circular references
// (C) 2017, Richard Marks. MIT License
// ccpsceo@gmail.com http://www.ccpssolutions.com
// use:
// const { deepCopy, runTests } = require('./deepCopy')
// const clone = deepCopy(source)
//
// quick test:
// const { deepCopy, runTests } = require('./deepCopy')
// runTests()
const deepCopy = source => {
if (source === undefined || source === null) {
return undefined
} else if (Array.isArray(source)) {
return source.map(element => deepCopy(element))
} else if (typeof source === 'object') {
const clone = Object.create({})
for (prop of Object.keys(source)) {
clone[prop] = deepCopy(source[prop])
}
return clone
} else if (typeof source === 'string' || source.constructor === String) {
return `${source}`
} else {
return source
}
}
const runTests = () => {
const assert = (name, desc, condition) => {
return new Promise((resolve, reject) => {
condition && resolve({ name, desc })
!condition && reject(new Error(`Assertion Failed: ${name} ${desc} is false`))
})
}
const source = {
child: {
grandchild: [
{
name: 'bobby'
},
{
name: 'matt'
}
]
}
}
const clone = deepCopy(source)
clone.child.grandchild[0].name = 'angela'
clone.child.grandchild.push({ name: 'johnny' })
assert(
'modifying clone does not modify original',
'clone.child.grandchild[0].name !== source.child.grandchild[0].name',
clone.child.grandchild[0].name !== source.child.grandchild[0].name
)
.catch(err => console.error(err))
.then(({ name, desc }) => {
console.log(`Assertion Passed: ${name} ${desc} is true`)
console.log(JSON.stringify(source, null, 2))
console.log(JSON.stringify(clone, null, 2))
})
}
module.exports = {
deepCopy,
runTests
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment