Skip to content

Instantly share code, notes, and snippets.

@ianpgall
Last active December 20, 2015 00:19
Show Gist options
  • Save ianpgall/6041330 to your computer and use it in GitHub Desktop.
Save ianpgall/6041330 to your computer and use it in GitHub Desktop.
JavaScript function that deep clones an Object or Array
var Clone = (function () {
"use strict";
var O, toString,
objType, arrType,
isObject, isArray,
each, iterator;
O = {};
toString = function (p) {
return O.toString.call(p);
};
objType = "[object Object]";
arrType = "[object Array]";
isObject = function (p) {
return (p !== null && toString(p) === objType);
};
isArray = function (p) {
return toString(p) === arrType;
};
each = function (obj, callback) {
var i, j, cur;
if (isObject(obj)) {
for (i in obj) {
cur = obj[i];
callback.call(cur, i, cur);
}
} else if (isArray(obj)) {
for (i = 0, j = obj.length; i < j; i++) {
cur = obj[i];
callback.call(cur, i, cur);
}
}
};
iterator = function (obj) {
var newObj;
if (isObject(obj) || isArray(obj)) {
newObj = obj.constructor();
each(obj, function (curKey, curVal) {
if (isObject(curVal) || isArray(curVal)) {
newObj[curKey] = iterator(curVal);
} else {
newObj[curKey] = curVal;
}
});
} else {
newObj = obj;
}
return newObj;
};
return iterator;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment