Created
December 3, 2014 16:26
-
-
Save briancavalier/c7f110ac65ce7b186f81 to your computer and use it in GitHub Desktop.
Recursively clone a JS Object or Array
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
| module.exports = clone; | |
| function clone(x) { | |
| if(x == null || typeof x !== 'object') { | |
| return x; | |
| } | |
| if(Array.isArray(x)) { | |
| return cloneArray(x); | |
| } | |
| return cloneObject(x); | |
| } | |
| function cloneArray (x) { | |
| var l = x.length; | |
| var y = new Array(l); | |
| for (var i = 0; i < l; ++i) { | |
| y[i] = clone(x[i]); | |
| } | |
| return y; | |
| } | |
| function cloneObject (x) { | |
| var keys = Object.keys(x); | |
| var y = {}; | |
| for (var k, i = 0, l = keys.length; i < l; ++i) { | |
| k = keys[i]; | |
| y[k] = clone(x[k]); | |
| } | |
| return y; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment