Skip to content

Instantly share code, notes, and snippets.

@fonji
Last active August 29, 2015 14:25
Show Gist options
  • Save fonji/dc279bbf23152d158fc4 to your computer and use it in GitHub Desktop.
Save fonji/dc279bbf23152d158fc4 to your computer and use it in GitHub Desktop.
Underscore recursive _.defaults (deepDefaults)
# _.deepDefaults
# inspired by _.defaults but adds recursivity
# https://gist.github.com/fonji/dc279bbf23152d158fc4
#
# Example:
# _.deepDefaults(
# {bar: {a: 'a', c: 'c'}},
# {foo: 'foo', bar: {a: 'b', d:'d'}}
# )
# will result in
# {bar: {a: 'a', c: 'c', d:'d'}, foo: 'foo'}
# Changelog:
# v0.1.0 creation (fonji)
_.mixin
# fn(original,newOne,anotherNewOne,...)
# works recursively for objects, not for arrays
deepDefaults: (original, newObj) ->
# TODO: make this work for more than one newObj
result = {}
for key, value of original
if newObj[key]? && _.isObject(value) && _.isObject(newObj[key])
result[key] = _.deepDefaults(value, newObj[key])
continue
result[key] = value
for key, value of newObj
continue if result[key]?
result[key] = value
result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment