Created
February 18, 2012 17:44
-
-
Save saidinesh5/1860351 to your computer and use it in GitHub Desktop.
A Useful coffeescript "defaults" function , which even does type checking.
This file contains hidden or 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
applyDefaults = (source, defaults) -> | |
### | |
# Recursively applies defaults to the source object | |
### | |
#The Mandatory safety checks | |
return source if not source? | |
return defaults if not defaults? | |
#First fill the results with defaults of each proprerty, recursively | |
result = {} | |
for prop of defaults | |
if not source[prop]? or typeof (defaults[prop]) isnt typeof (source[prop]) | |
result[prop] = defaults[prop] | |
#Another check as Javascript Arrays are just javascript objects with integer keys | |
else if typeof (defaults[prop]) is "object" and not _.isArray defaults[prop] | |
result[prop] = applyDefaults(source[prop], defaults[prop]) | |
#Then Fill in the holes of defaults with the values from source | |
for prop of source | |
result[prop] = source[prop] unless result[prop]? | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment