1

Does coffeescript offer an equivalent for "else" within array comprehensions like python's list comprehensions?

Python example

foo = ["yes" if i < 50 else "no" for i in range(100)]

Since, in python, the if/else is actually a ternary statement, I figured coffeescript might be similar, so I tried this:

coffeescript attempt

foo = (if i < 50 then "yes" else "no" for i in [0..100])

The difference is that python appropriately gives me 50 yes's and 50 no's, but coffeescript only gives me a single "yes".

So, just to be clear, I want to know if there is a way to use an "else" in coffeescript's array comprehensions.

2 Answers 2

4

Your original query transpiles to this:

var _i, _results;
if (i < 50) {
  return "yes";
} else {
  _results = [];
  for (i = _i = 0; _i <= 100; i = ++_i) {
    _results.push("no");
  }
  return _results;
}

As you can see, the i < 50 is met immediately since it's undefined, which returns a single "yes".

You need to rewrite it this way to get the desired result:

foo = ((if i < 50 then "yes" else "no") for i in [0..100])

This results in the following:

for (i = _i = 0; _i <= 100; i = ++_i) {
  _results.push(i < 50 ? "yes" : "no");
}
Sign up to request clarification or add additional context in comments.

Comments

1

New lines and indention also work. Turning a loop into a comprehension is almost too easy in Coffeescript.

x = for i in [0..100]
   if i<50 then 'yes' else 'no'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.