Skip to content

Instantly share code, notes, and snippets.

@caridy
Created January 22, 2013 18:08
Show Gist options
  • Select an option

  • Save caridy/4596751 to your computer and use it in GitHub Desktop.

Select an option

Save caridy/4596751 to your computer and use it in GitHub Desktop.
Experimenting with deep merge leveraging prototypal inheritance instead of pure JSON objects for YCB
function heir (o) {
function F() {}
F.prototype = o;
return new F();
}
function heirDeep (o) {
var dest,
i;
dest = heir(o);
for (i in o) {
if (o.hasOwnProperty(i) && o[i] && typeof o[i] === 'object') {
dest[i] = heirDeep(o[i]);
}
}
return dest;
}
function heirDeepMerge (o, overlay) {
var dest,
i;
overlay = overlay || {};
dest = heir(o);
for (i in o) {
if (overlay.hasOwnProperty(i) && typeof overlay[i] !== 'object') {
dest[i] = overlay[i]; // null, undefined, overruling an obj with a value, etc
} else if (o.hasOwnProperty(i) && o[i] && typeof o[i] === 'object') {
dest[i] = heirDeepMerge(o[i], overlay[i]);
} else if (overlay.hasOwnProperty(i)) {
dest[i] = overlay[i];
}
}
return dest;
}
function merge (heir, overlay) {
var i;
overlay = overlay || {};
for (i in heir) {
if (overlay.hasOwnProperty(i) && typeof overlay[i] !== 'object') {
heir[i] = overlay[i]; // null, undefined, overruling an obj with a value, etc
} else if (heir[i] && typeof heir[i] === 'object') {
heir[i] = merge(heir[i], overlay[i]);
} else if (overlay.hasOwnProperty(i)) {
heir[i] = overlay[i];
}
}
return heir;
}
var from = {a: 1, b: 2, c: { d: 3 }};
var to = {a: 'a', c: {e: 4} };
var b = {c: 1};
var test1 = heir({
a: 1,
b: heir(b)
});
console.log('A: ', test1.a, test1.b.c, b.c);
test1.a = 2;
test1.b.c = 2;
console.log('B: ', test1.a, test1.b.c, b.c);
var origin = {
a: 1,
b: {c: 1}
};
var test2 = heirDeep(origin);
console.log('C: ', test2.a, test2.b.c, origin.b.c);
test2.a = 2;
test2.b.c = 2;
console.log('D: ', test2.a, test2.b.c, origin.b.c);
var base = {
a: 1,
b: {c: 1}
};
var overlay = {
a: 2,
b: {
c: 2
}
};
var test3 = heirDeepMerge(base, overlay);
console.log('E: ', test3.a, test3.b.c, base.b.c);
var cacheable = {
a: 1,
b: {c: 1}
};
var secure = {
a: 2,
b: {
c: 2
}
};
var test4 = merge(heirDeep(cacheable), secure);
console.log('F: ', test4.a, test4.b.c, cacheable.b.c);
test4.b.c = 3;
console.log('G: ', test4.b.c, cacheable.b.c, secure.b.c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment