Skip to content

Instantly share code, notes, and snippets.

@jimmont
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmont/035e399ea5d1a7ffc1fe to your computer and use it in GitHub Desktop.
Save jimmont/035e399ea5d1a7ffc1fe to your computer and use it in GitHub Desktop.
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