1

I am new in CoffeeScript (I started learning this morning) and the only thing that I am not able to find is an elegant way to split an array in subarrays. For example, I have the following array:

myarr = [1, 7, 8, 3, 5, 1, 4, 9, 0, 2]

And I want to split it in subarrays of two elements each one:

myarr = [[1, 7], [8, 3], [5, 1], [4, 9], [0, 2]]

I know how to do it with pure javascript however, and given I am learning, I was not able to find an elegant-coffeescript way. Does CoffeeScript allow a nice solution for this?

Update:

using the http://js2coffee.org/ site to translate my javascript code to CoffeScript I was able to find this solution:

Array::chunk = (chunkSize) ->
  array = this
  [].concat.apply [], @map((elem, i) ->
    (if i % chunkSize then [] else [array.slice(i, i + chunkSize)])
  )

It looks quite right. But that is a translator output and not a expert recommendation.

Disclaimer:

Even when CoffeeScript compiles to Javascript, I am looking for a CoffeeScript solution and not a Javascript solution. The idea that "if you know javascript then, you know coffeescript" is not true for me, at least not yet.

lontivero
  • 5,235
  • 5
  • 25
  • 42
  • 2
    @Iontivero: If you know the solution in pure JavaScript, you may want to try some converter like http://js2coffee.org. It may help a lot in the beggining. – Dhanu Gurung Dec 18 '13 at 03:06
  • This doesn't make sense. Implementing the same algorithm in CoffeeScript is trivial, and probably the best way for you to go about learning a little more CoffeeScript. If you can solve this in JavaScript, you can solve it in CoffeeScript. – user229044 Dec 18 '13 at 03:14
  • I was about to post an answer, but I guess this will have to suffice: try `result = [[], []] * i = 0 * * while i < yourArray.length * result[i & 1].push yourArray[i] * i++ *` (where * equals a line break) – T145 Dec 18 '13 at 03:22
  • Remember that Coffee Script is essentially shorthand JavaScript that is compiled as JavaScript somewhere in the workflow (don't know/care where). So really you should refactor this question so that you're asking, `how can I write [some expressions] JavaScript in CoffeeScript?` – shennan Dec 18 '13 at 03:22
  • Thank you, @budhram! That is a fantastic tool, very useful ;) – lontivero Dec 18 '13 at 03:22

0 Answers0