CoffeeScript idiom for Array.reduce with default v

2019-07-15 11:20发布

问题:

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?

回答1:

I've run in to this myself with other functions. In cases where its really made a mess of things (or it just really bothers me), I might declare the function elsewhere (perhaps above that line), and then pass the function as a parameter, something like so:

reduce_callback = (memo, item) ->
    memo[item.id] = item
    memo

itemsById = items.reduce reduce_callback, {}

Unfortunately, you expand a whole lot vertically, which may or may not be desirable. This is merely a general suggestion.



回答2:

This works:

itemsById = items.reduce (memo, item) ->
  memo[item.id] = item
  memo
, {}


回答3:

items = [ {id:'id1', name:'Foo'}, {id:'id2', name:'Bar'} ]
itemsById = {}
itemsById[item.id] = item for item in items

Clean and readable.