Created
March 21, 2014 11:21
-
-
Save roboncode/9684114 to your computer and use it in GitHub Desktop.
A simple diff function in JavaScript. Does not try to diff arrays. Requires "underscore" or "lodash"
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
// Requires either "underscore" or "lodash" | |
function difference(source, compare) { | |
var ret = {}, dateStr; | |
for (var name in compare) { | |
if (name in source) { | |
if (_.isDate(compare[name])) { | |
dateStr = _.isDate(source[name]) ? source[name].toISOString() : source[name]; | |
if (compare[name].toISOString() !== dateStr) { | |
ret[name] = compare[name]; | |
} | |
} else if (_.isObject(compare[name]) && !_.isArray(compare[name])) { | |
var diff = difference(source[name], compare[name]); | |
if (!_.isEmpty(diff)) { | |
ret[name] = diff; | |
} | |
} else if (!_.isEqual(source[name], compare[name])) { | |
ret[name] = compare[name]; | |
} | |
} else { | |
ret[name] = compare[name]; | |
} | |
} | |
if (_.isEmpty(ret)) { | |
return null; | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment