Skip to content

Instantly share code, notes, and snippets.

@m1el
Last active December 17, 2015 22:49
Show Gist options
  • Save m1el/5684321 to your computer and use it in GitHub Desktop.
Save m1el/5684321 to your computer and use it in GitHub Desktop.
Deep object clone without recursion with recursion objects check
var fork = function (source, unsafe) {
var
objmap = unsafe ? null : new Map(),
targetOut = {__proto__: source.__proto__},
target,
stack = {0: {source: source, target: targetOut}},
sp = 0,
ss = 1,
keys, key, j, scope, tmp;
while ((scope = stack[sp++])) {
keys = Object.keys(scope.source);
j = keys.length;
while (j--) {
source = scope.source[key = keys[j]];
if (source !== null && source === Object(source)) {
if (!unsafe && (tmp = objmap.get(source))) {
scope.target[key] = tmp;
} else {
scope.target[key] = target = {__proto__: source.__proto__};
stack[ss++] = {source: source, target: target};
if (!unsafe) {
objmap.set(source, target);
}
}
} else {
scope.target[key] = source;
}
}
delete stack[sp - 1];
}
target = source = stack = keys = key = scope = null;
return targetOut;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment