James M. Lay
James M. Lay

Reputation: 2470

Coffeescript: "else" within array comprehension

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.

Upvotes: 1

Views: 351

Answers (2)

hpaulj
hpaulj

Reputation: 231530

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'

Upvotes: 1

Ahmad Mageed
Ahmad Mageed

Reputation: 96507

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");
}

Upvotes: 4

Related Questions