Skip to content

Instantly share code, notes, and snippets.

@jimmont jimmont/diff
Last active Aug 29, 2015

Embed
What would you like to do?
what changed from the default
function diff(defaults, customs, diffs){
/**
* @description
compare an object against the default returning an object with the differences
in the customs object separated out in the returned value
when there are no unique values in the customs object undefined is returned
* @returns
diff value, when no differences undefined, when an object returns object with keys and other values
* @example
usr.diff(defaults, custom);
usr.diff({a:1,zeb:[7]},{b:2,zeb:[1,2,3]})
returns {b:2, zeb:[1,2,3]}
*/
diffs = diffs || {};
function diffr(defaults, customs, result){
// return what's different in customs
var alt, key, item, ckeys;
try{
// only objects have keys
ckeys = Object.keys( customs );
}catch(customNotAnObject){
// customs isn't an object here, compare primitives strictly
if(defaults === customs) return;
else return customs;
};
// look through customs for overwritten things
while(key = ckeys.shift()){
item = defaults[ key ];
// values missing from default, not already checked, are only on customs
if(typeof item === 'undefined'){
result[ key ] = customs[ key ];
continue;
};
alt = customs[key];
item = diffr( item, alt, {});
if(typeof item !== 'undefined'){
result[ key ] = item;
};
};
item = key = ckeys = 0;
if(!/\[]|{}/.test(JSON.stringify(result))) return result;
};
return diffr(defaults, customs, diffs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.