Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top