Skip to content

Instantly share code, notes, and snippets.

@mzgoddard
Created April 13, 2017 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzgoddard/5d7faa14aad848fa0c9c0e102168b215 to your computer and use it in GitHub Desktop.
Save mzgoddard/5d7faa14aad848fa0c9c0e102168b215 to your computer and use it in GitHub Desktop.
Shallow object difference
// Create a difference of entries in an object when that object
// does not equal the new value shallowly.
//
// Example:
// a0 = {a: {b: {c: 3}, d: 4}}; a1 = {a: {b: a0.a.b, d: 5}};
// diff(a0, a1) = {a: {d: 5}};
const diff = (a, b) => {
let o;
if (a !== b) {
if (typeof b === 'object' && !Array.isArray(b)) {
o = {};
for (let key in b) {
const result = diff(a[key], b[key]);
if (typeof result !== 'undefined') {
o[key] = result;
}
}
for (let key in a) {
if (!(key in b)) {
o[key] = undefined;
}
}
}
else {
o = b;
}
}
return o;
}
const patch = (a, b) => {
if (typeof b === 'object' && !Array.isArray(b)) {
const o = {};
for (let key in a) {
if (!(key in b)) {
o[key] = a[key];
}
}
for (let key in b) {
if (typeof b[key] !== 'undefined') {
o[key] = patch(a[key], b[key]);
}
}
return o;
}
return b;
}
let a0 = {a: 0};
let a1 = {};
diff(a0, a1);
patch(a0, diff(a0, a1));
let b0 = {a: {b: {c: 3}, d: 4}};
let b1 = {a: {b: b0.a.b, d: 5}};
diff(b0, b1);
patch(b0, diff(b0, b1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment