用于循环重构的coffeescript

用于循环重构的coffeescript,coffeescript,Coffeescript,我对coffeescript非常陌生,我想知道是否有更有经验的用户可以建议对以下代码进行重构: splitCollection: => maxLength = Math.ceil(@collection.length / 3) sets = Math.ceil(@collection.length / maxLength) start = 0 for x in [1..sets] if x != sets @render new Bus

我对coffeescript非常陌生,我想知道是否有更有经验的用户可以建议对以下代码进行重构:

splitCollection: =>
  maxLength = Math.ceil(@collection.length / 3)

  sets = Math.ceil(@collection.length / maxLength)
  start = 0    

  for x in [1..sets]   
    if x != sets
      @render new BusinessUnits(@collection.models.slice(start, (maxLength + start)))
    else
      @render new BusinessUnits(@collection.models.slice(start, (@collection.length)))
    start+= maxLength
咖啡脚本中似乎没有while循环,这似乎暗示了一种更好的机制


非常感谢您的建议。

看起来您正在使用Backbone.js,其中包括underline.js,它具有
groupBy
功能

您可以创建一个“bucketNumber”函数:

bucketNumber = (value, index) ->
    Math.floor( index / @collection.length * 3 )
然后将您的收藏分组:

sets = @collection.groupBy bucketNumber
现在,假设有十项,
集合
应该如下所示:

{0: [{}, {}, {}], 1: [{}, {}, {}], 2: [{}, {}, {}, {}]}
从这里开始,它变得相当直截了当

for bucketNumber, bucket of sets
    @render new BusinessUnits( bucket )

下面是一个演示动作的示例

您不需要两次跟踪您的位置,
x
就足够了:

splitCollection: =>
    setSize = Math.ceil @collection.length / 3
    sets = Math.ceil @collection.length / maxLength

    for x in [1..sets]
        @render new BusinessUnits @collection.models[x * setSize...(x+1) * setSize]

请注意,传递
切片
一个大于数组长度的端点没有错。

如果我理解您的代码,您希望将数组拆分为3部分(最后一部分可以包含较少的项)。在本例中,为任务编写可重用的抽象。使用:

的inGroupsOf可以写为:

_.mixin({
  inGroupsOf: function(array, n) {
    var output = [];
    for(var index=0; index < array.length; index += n) {
      output.push(array.slice(index, index+n));
    }
    return output;
  }
});
混合({
inGroupsOf:函数(数组,n){
var输出=[];
对于(变量索引=0;索引
这是一个很好的答案,我可能会使用它,但我正在努力更好地理解coffeescript。
_.mixin({
  inGroupsOf: function(array, n) {
    var output = [];
    for(var index=0; index < array.length; index += n) {
      output.push(array.slice(index, index+n));
    }
    return output;
  }
});