I am quite new to coffeescript and I am wondering if any more experienced users could point suggest a refactoring for the following code:
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
There does not appear to be a while loop in coffeescript which seems to suggest a better mechanism.
Any suggestions appreciated.
Looks like you are using Backbone.js, which includes Underscore.js, which has the
groupByfunction.You could create a “bucketNumber” function:
Then group your collection:
Now, assuming ten items,
setsshould look something like this:From here, it becomes rather straight-forward
Here is a jsFiddle showing it in action