tig
tig

Reputation: 27790

Cycle using method in CoffeeScript

Given I have two objects lower and upper of same type and they return successive value using method succ (as in ruby) and can be compared using <.

In plain javascript I can write:

for (var i = lower; i <= upper; i = i.succ()) {
  // …
}

Using prototype I can write shorter:

$R(lower, upper).each(function(i){
  // …
}, this)

Using prototype in coffeescript I can write even shorter:

$R(lower, upper).each (i)->
  # …
, this

But without prototype, I found only this way to do same thing:

i = lower
while i <= upper
  # …
  i = i.succ() 

Is there anything shorter?

Upvotes: 2

Views: 402

Answers (2)

Jacob Oscarson
Jacob Oscarson

Reputation: 6393

How about:

while upper >= n = i.succ()
  alert n

Try it here, for the example I used the following fixture:

upper = 3
lower = 0

counter = (l) ->
  _ = l
  -> _++

i = succ: counter(lower)

/me still wishing for widespread generator support in Javascript..

Upvotes: 0

Trevor Burnham
Trevor Burnham

Reputation: 77416

I think you are correct that

i = lower
while i < upper
  # …
  i = i.succ()

is the shortest way to write this without using a function. Of course, you could write such a function without using Prototype:

eachSucc = (lower, upper, func) ->
  i = lower
  while i < upper
    func i
    i = i.succ()

Then you can call it like so:

eachSucc lower, upper, (i) -> ...

Upvotes: 1

Related Questions