Created
April 13, 2017 20:22
-
-
Save mzgoddard/5d7faa14aad848fa0c9c0e102168b215 to your computer and use it in GitHub Desktop.
Shallow object difference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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