While the loop in CoffeeScript

I am new to CoffeeScript and am reading a book, CoffeeScript Little Book . Here are a few lines from Chapter 2 that confused me as I read:

The only low-level loop that CoffeeScript provides is the while loop. This is similar to a while loop in pure JavaScript, but has the added benefit of returning an array of results, i.e. Like Array.prototype.map () function.

num = 6
minstrel = while num -= 1
  num + " Brave Sir Robin ran away"

      

While it may look good to a CoffeeScript programmer, as a beginner, I can't figure out what the code is doing. Moreover, the words return an array of results does not seem to be the same as while is a loop string, not a function. Thus, the concept of return seems to be something incomprehensible. In addition, a variable num

with a string "Brave Sir Robin ran away"

at each iteration of the loop seems inconvenient, since the value is num

used as a loop counter.

I would appreciate it if you could explain the behavior of the code and perhaps illustrate what the author is trying to convey with simpler examples.

+3


source to share


2 answers


Wow! I didn't know this, but it makes sense if you remember that Coffeescript always returns the last "block" expression. So in your case it returns (not via the "return" statement, if that's what confuses you) the expression

 num + " Brave Sir Robin ran away" 

      

from the block associated with the while condition, and since you will return multiple such expressions, it pushes them towards the array.



Have a look at the generated JavaScript and it may be clearer since the generated code is pretty much procedural

var minstrel, num;

num = 6;

minstrel = (function() {
    var _results;
    _results = [];
    while (num -= 1) {
        _results.push(num + " Brave Sir Robin ran away");
    }
    return _results;
})();

      

I hope this makes sense to you.

+5


source


Beware, this function call can be very inefficient!

Below is the prime factor generator

'use strict'

exports.generate = (number) ->
  return [] if number < 2
  primes = []
  candidate = 1
  while number > 1
    candidate++
    while number % candidate is 0
      primes.push candidate
      number /= candidate
    candidate = number - 1 if Math.sqrt(number) < candidate
  primes

      



This is the version using while

as expression

'use strict'

exports.generate = (number) ->
  return [] if number < 2
  candidate = 1
  while number > 1
    candidate++
    primes = while number % candidate is 0
      number /= candidate
      candidate
    candidate = number - 1 if Math.sqrt(number) < candidate
  primes

      

The first version ran my tests in 4 milliseconds, the last one in 18 milliseconds. I believe the reason is the generated closure that returns prime numbers.

+1


source







All Articles