Skip to content

Instantly share code, notes, and snippets.

@sheldonh
Last active February 29, 2024 15:51
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sheldonh/6089299 to your computer and use it in GitHub Desktop.
Save sheldonh/6089299 to your computer and use it in GitHub Desktop.
CoffeeScript Object.merge
merge = (xs...) ->
if xs?.length > 0
tap {}, (m) -> m[k] = v for k, v of x for x in xs
tap = (o, fn) -> fn(o); o
console.log merge {foo: '1', bar: 'baz'}, {bar: 'bis'} , {wombat: 'fishpaste'}
###
{ foo: '1', bar: 'bis', wombat: 'fishpaste' }
###
@pke
Copy link

pke commented Aug 16, 2014

Thanks, very neat. And works, unlike the CoffeeScript helper method displayed here http://coffeescript.org/documentation/docs/helpers.html
Which is strange, since its part of the compiler... hmmm

@bogdan
Copy link

bogdan commented Nov 23, 2015

Nice, I can make it even more neat:

merge=(xs... ->
  if xs?.length>0
    tap {},(m)->m[k]=v for k,v of x for x in xs
tap=(o, fn)->fn(o);o

But thanks anyway.

@alexbfree
Copy link

This is really handy - thanks. Could you explain line 5? I didn't know semi-colon was allowed in coffeescript....

@thislooksfun
Copy link

@alexbfree Semicolons are fully optional in CS. (console.log "hi" and console.log "hi"; are both 100% valid), but they are still the only way to fit multiple statements on the same line.

To quote the coffeescript website directly:
"You don’t need to use semicolons ; to terminate expressions, ending the line will do just as well (although semicolons can still be used to fit multiple expressions onto a single line)." (source)

@sixtyfive
Copy link

The version by @bogdan (23 Nov 2015) unfortunately doesn't compile for me. The original version works fine, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment