Skip to content

Instantly share code, notes, and snippets.

@roboncode
Created March 21, 2014 11:21
Show Gist options
  • Save roboncode/9684114 to your computer and use it in GitHub Desktop.
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"
// 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