2

I'm looking to optimize a loop without using a boolean conditional to check whether to perform some action if the loop terminates normally without breaking. In python I'd write this:

for x in lst:
    if cond(x):
       do_stuff_with(x)
       break
else:
    do_other_stuff()

In Coffeescript the best I can think of is to do something like this:

found = false
for x in lst
    if cond x
        found = true
        do_stuff_with x
        break
if not found
    do_other_stuff()

Is there a Coffeescript idiom for this situation?

2rs2ts
  • 10,662
  • 10
  • 51
  • 95
  • Since a for loop compiles to `for (_i = 0, _len = lst.length; _i < _len; _i++)`, you could, in theory, compare `_i` with `_len` to check for a break (or its absence). But boolean flag is more transparent. – hpaulj Jan 01 '14 at 04:03

1 Answers1

3

For this certain usage, you can use EcmaScript 6 .find function. Similar method exists in Underscore.js, if you want to be compatible with browsers not supporting EcmaScript 6.

result = lst.find cond
if result?
  do_stuff_with result
else
  do_other_stuff()

However, there is no direct replacement for for else loop from Python. In general case, you will need to declare a boolean to store the state.

Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71
  • For a second there, I thought you wrote ruby. – Games Brainiac Dec 31 '13 at 16:55
  • 1
    @GamesBrainiac: Well, technically CoffeeScript was heavily inspired by Ruby, so this is to be expected. But it's not Ruby, even if it looks like Ruby (for example, Ruby doesn't have postfix `?` operator (but it does have `.nil?` which does the opposite thing)). – Konrad Borowski Dec 31 '13 at 16:57
  • I'm already using underscore so I'll use their `_.find`, thanks. I submitted a request to the coffeescript repo for such a language construct in the meantime. – 2rs2ts Dec 31 '13 at 17:07
  • `loDash` `forEach` loop allows an early exit (if the callback returns `false`), but I don't see a neat way of capturing that event. – hpaulj Jan 01 '14 at 04:16