Last active
August 29, 2015 14:01
-
-
Save four43/f93647e8feaa54713cfe to your computer and use it in GitHub Desktop.
Javascript Deep Copy with Depth
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
/** | |
* Deep Copy | |
* | |
* Creates a new object, copying the variables one by one into it. | |
* Available as a GitHub Gist: https://gist.github.com/four43/f93647e8feaa54713cfe | |
* @param {Object|Array} input The input object or array to copy. | |
* @param {Number} [maxDepth] The max depth the function should recurse before passing by reference, default: 5 | |
* @param {Number} [depth] Starts at 0, used by recursion | |
* @returns {Object|Array} | |
* @private | |
*/ | |
Object.prototype._deepCopy = function (input, maxDepth, depth) { | |
if (maxDepth === undefined) { | |
maxDepth = 5; | |
} | |
if (depth === undefined) { | |
depth = 0; | |
} | |
if(depth > maxDepth) { | |
return null; | |
} | |
// Handle the 3 simple types, and null or undefined | |
if (input === null || input === undefined || typeof input !== "object") { | |
return input; | |
} | |
// Date | |
if (input instanceof Date) { | |
var dateCopy = new Date(); | |
dateCopy.setTime(input.getTime()); | |
return dateCopy; | |
} | |
// Array | |
if (input instanceof Array) { | |
var arrayCopy = []; | |
for (var i = 0, len = input.length; i < len; i++) { | |
arrayCopy[i] = this._deepCopy(input[i], maxDepth, depth + 1); | |
} | |
return arrayCopy; | |
} | |
// Object | |
if (input instanceof Object) { | |
var newObj = {}; | |
for (var prop in input) { | |
if (input.hasOwnProperty(prop)) newObj[prop] = this._deepCopy(input[prop]); | |
} | |
return newObj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added comment section.