Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript idiom for Array.reduce with default value

Tags:

coffeescript

In CoffeeScript sometimes I need to call Array.reduce(...) with a default value; however, the unfortunate ordering of the arguments means the initial/default value goes after the reduce function itself, which means I've got to use a lot of parens, which seems much uglier than CoffeeScript wants to be.

For example:

items = [ (id:'id1', name:'Foo'), (id:'id2', name:'Bar') ] # ...
itemsById = items.reduce(((memo, item) -> # <-- Too many parens!
  memo[item.id] = item
  memo), {}) # Ugly!

Is there a more idiomatic way to do this in CS?

like image 951
maerics Avatar asked Dec 20 '22 17:12

maerics


1 Answers

This works:

itemsById = items.reduce (memo, item) ->
  memo[item.id] = item
  memo
, {}
like image 79
mash Avatar answered Feb 23 '23 15:02

mash