Created
April 1, 2019 01:16
-
-
Save ositowang/cd56a78b237f94a15a6540a4a4ff1e9a to your computer and use it in GitHub Desktop.
More comprehensive deepclone with JS. Cover null and Array.
This file contains 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
/** | |
* You should be good with this solution | |
* More comprehensive deepclone with JS. Cover null and Array. | |
* Problems: | |
* 1. did not solve the circular dependency | |
* @param {Object} sourceObj | |
* @returns | |
*/ | |
var deepCloneBetter = (sourceObj) => { | |
// if we are not dealing with complex data structure | |
if (typeof sourceObj !== 'object' && sourceObj !== null) { | |
return sourceObj; | |
} | |
let result = Array.isArray(sourceObj) ? [] : {}; | |
for (let key in sourceObj) { | |
//ignore the prototype chain | |
if (Object.prototype.hasOwnProperty.call(sourceObj, key)) { | |
if (typeof sourceObj[key] !== 'object' && sourceObj[key] !== null) { | |
result[key] = deepCloneBetter(sourceObj[key]); | |
} else { | |
result[key] = sourceObj[key]; | |
} | |
} | |
} | |
return result; | |
}; | |
// more elegant version with Functional programming with 30s javascript version | |
const deepClone = (obj) => { | |
let clone = Object.assign({}, obj); | |
Object.keys(clone).forEach( | |
(key) => | |
(clone[key] = | |
typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]), | |
); | |
return Array.isArray(obj) && obj.length | |
? (clone.length = obj.length) && Array.from(clone) | |
: Array.isArray(obj) | |
? Array.from(obj) | |
: clone; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment