CoffeeScript idiom for Array.reduce with default v

2019-07-15 11:36发布

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?

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-15 12:13

This works:

itemsById = items.reduce (memo, item) ->
  memo[item.id] = item
  memo
, {}
查看更多
我命由我不由天
3楼-- · 2019-07-15 12:23
items = [ {id:'id1', name:'Foo'}, {id:'id2', name:'Bar'} ]
itemsById = {}
itemsById[item.id] = item for item in items

Clean and readable.

查看更多
仙女界的扛把子
4楼-- · 2019-07-15 12:27

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.

查看更多
登录 后发表回答