Created
March 20, 2016 12:54
-
-
Save mattisa/b457d4f25131e6e9255d to your computer and use it in GitHub Desktop.
Get nested json diff. this is just initial version to store for later use.
This file contains 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
module helpers { | |
'use strict'; | |
export class DiffHelper { | |
public diff(a, b, seed = {}) { | |
const keys = this.arrayUnique(Object.keys(a).concat(Object.keys(b))); | |
return keys.reduce((delta = {}, key) => { | |
if (a.hasOwnProperty(key) && b.hasOwnProperty(key)) { | |
// both has property | |
const type = typeof a[key]; | |
if (type === 'object') { | |
// if has children, calculate diff | |
const childDelta = this.diff(a[key], b[key]); | |
if (childDelta !== undefined && Object.keys(childDelta).length > 0) { | |
delta[key] = childDelta; | |
} | |
} else if (type !== 'function' && a[key] !== b[key]) { | |
// skip function function and set value | |
delta[key] = b[key]; | |
} | |
} else if (a.hasOwnProperty(key) && !b.hasOwnProperty(key)) { | |
// property has removed | |
delta[key] = undefined; | |
} else if (!a.hasOwnProperty(key) && b.hasOwnProperty(key)) { | |
// property has added | |
delta[key] = b[key]; | |
} | |
if (Object.keys(delta).length > 0) { | |
return delta; | |
} else { | |
return undefined; | |
} | |
}, seed); | |
} | |
private arrayUnique(a) { | |
return a.reduce(function(p, c) { | |
if (p.indexOf(c) < 0) p.push(c); | |
return p; | |
}, []); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment