Last active
November 19, 2015 17:32
-
-
Save ecasilla/89e2154fe1c935f41b98 to your computer and use it in GitHub Desktop.
Js Object Diff
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
import * as _ from 'lodash'; | |
function objectDiff(prev, now){ | |
// sanity checks, prev and now must be an object. | |
if ( ! _.isObject(prev) || ! _.isObject(now) ){ | |
return new TypeError("Arguments must both be objects",__filename); | |
} | |
var changes = {}; | |
for (var prop in now) { | |
// if property is new in now i.e unknown, add it too changes | |
if (!prev || !prev.hasOwnProperty(prop) ) { | |
changes[prop] = now[prop]; | |
continue; | |
} | |
// if the property has another type or value (different object or literal) | |
if (prev[prop] !== now[prop]) { | |
if ( _.isArray(now[prop]) ) { | |
// add the new array if not equal or continue on to next iteration | |
if(!_.isEqual(prev[prop], now[prop] ) ){ | |
changes[prop] = now[prop]; | |
}else { | |
continue; | |
} | |
} else if (_.isObject( now[prop] ) ) { | |
// the property is an object, so recurse into ourselves with this key | |
var c = objectDiff(prev[prop], now[prop]); | |
if (! _.isEmpty(c) ) | |
changes[prop] = c; | |
} else { | |
// now[prop] has different primitive value, i.e bool string number | |
changes[prop] = now[prop]; | |
} | |
} | |
} | |
// returns empty object if nothing changed | |
return changes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment