CoffeeScript idiom for Array.reduce with default value

泪湿孤枕 提交于 2019-12-12 16:19:41

问题


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.



来源:https://stackoverflow.com/questions/22028924/coffeescript-idiom-for-array-reduce-with-default-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!