Skip to content

Instantly share code, notes, and snippets.

@saidinesh5
Created February 18, 2012 17:44
Show Gist options
  • Save saidinesh5/1860351 to your computer and use it in GitHub Desktop.
Save saidinesh5/1860351 to your computer and use it in GitHub Desktop.
A Useful coffeescript "defaults" function , which even does type checking.
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