本文介绍了使用默认值Array.reduce的CoffeeScript成语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CoffeeScript中,有时我需要调用;然而,参数的不幸排序意味着初始/默认值在reduce函数本身之后,这意味着我必须使用大量的括号,这看起来比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.

例如:

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

在CS中有更多惯用的方法吗?

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

推荐答案

我自己和其他函数一起运行。如果它真的做了一些东西(或者它只是真的困扰我),我可能声明函数在其他地方(也许在该行之上),然后传递函数作为参数,像这样:

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.

这篇关于使用默认值Array.reduce的CoffeeScript成语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:14