Last active
January 1, 2016 22:09
-
-
Save CharlesAnifowose/8208577 to your computer and use it in GitHub Desktop.
Similar intention as Underscore's _.defaults() algorithm, but with the ability to go deep into objects.
Function will error out if Objects have circular references. Dependencies: UnderscoreJS
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
function deepDefault(obj, source, depth, blankCheck){ | |
if (depth===undefined){ | |
depth=0; | |
} | |
if (depth>1000){ | |
throw new Error('Too many iterations, possible circular reference'); | |
return; | |
} | |
_.each(source, function(sourceVal, i){ | |
var val = obj[i]; | |
if (_.isFunction(val)){ | |
// do nothing | |
} | |
else if (_.isObject(val)){ | |
if( _.isObject(sourceVal) && !_.isFunction(sourceVal) ){ | |
deepDefault(val, sourceVal, depth+1, blankCheck); | |
} | |
} | |
else if (val===undefined){ | |
if( _.isObject(sourceVal) && !_.isFunction(sourceVal) ){ | |
obj[i]={}; | |
deepDefault(obj[i], sourceVal, depth+1, true); | |
} | |
else{ | |
obj[i] = sourceVal; | |
} | |
} | |
}) | |
} | |
var a = {dog:'woof', cat:{sleepy:'purr'} }; | |
var b = {mouse:'squeak', cat:{awake:'meow'}}; | |
deepExtend(a,b); | |
console.log(a); | |
// {dog:'woof', cat:{sleepy:'purr', awake:'meow'}, mouse:'squeak'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Had to be careful with the functions that look like objects!