Created
May 1, 2011 09:30
-
-
Save Sija/950370 to your computer and use it in GitHub Desktop.
Object.merge
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
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