Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mdarse/6132692 to your computer and use it in GitHub Desktop.
Save mdarse/6132692 to your computer and use it in GitHub Desktop.
function cloneObject(object) {
return extendObject({}, object);
}
function extendObject(base, object) {
var visited = [object];
// http://en.wikipedia.org/wiki/Adjacency_list_model
var set = [{value: base}];
_extend(base, object);
return base;
function _extend(base, object) {
for (var key in object) {
var value = object[key];
if (typeof value === 'object') {
var index = visited.indexOf(value);
if (index === -1) {
visited.push(value);
var newBase = base[key] = {};
set.push({up: base, value: newBase});
_extend(newBase, value);
} else {
base[key] = set[index].value;
}
} else {
base[key] = value;
}
}
}
}
// Example #1
var a = {};
a.self = a;
console.log(a, cloneObject(a));
// Example #2
var b = {
x: 1,
y: {
y1: 2,
z1: {
z2: 3
}
}
};
b.top = b;
b.y.top = b;
b.y.z1.top = b;
b.y.up = b;
b.y.z1.up = b.y;
b.y.z1.self = b.y.z1;
var bClone = cloneObject(b);
bClone.x = 42;
bClone.y.y1 = 13;
console.log(b, bClone);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment