Skip to content

Instantly share code, notes, and snippets.

@Sija
Created May 1, 2011 09:30
Show Gist options
  • Save Sija/950370 to your computer and use it in GitHub Desktop.
Save Sija/950370 to your computer and use it in GitHub Desktop.
Object.merge
merge = (target, objects...) ->
deep = yes
if typeof target is 'boolean'
[deep, target] = [target, objects.shift()]
if not objects.length
[target, objects] = [this, [target]]
isExtendable = (object) ->
typeof object is 'object' and object isnt null or
typeof object is 'function' or
Array.isArray(object)
target = {} unless isExtendable target
for object in objects
continue unless isExtendable object
for key, copy of object
continue unless Object::hasOwnProperty.call object, key
if deep and isExtendable copy and target isnt copy
src = target[key]
if Array.isArray copy
clone = Array.isArray(src) and src or []
clone.push copy...
copy = clone
else
copy = arguments.callee deep, src, copy
target[key] = copy
target
reverse_merge = (objects...) ->
return {} if not objects.length
if typeof objects[0] is 'boolean'
merge objects.shift(), objects.reverse()...
else
merge objects.reverse()...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment