Does the shorter comprehension syntax require a range as a source?

67 Views Asked by At

I would like to create an array initialized to all zeros, with the same length as another array. I've heard that new Array(baz.length) isn't recommended because the array constructor is ambiguous. (see this answer) No matter, for CoffeeScript has beautiful array comprehensions! For example, this works:

foo = (0 for i in baz)

This is readable and concise, and I'm happy. (Hooray CoffeeScript!) But I really don't need the current iteration value in this case. I just need an element for each element in baz. The CoffeeScript documentation states

If you don't need the current iteration value you may omit it:

browser.closeCurrentTab() for [0...count]

So I should be able to say

foo = (0 for baz)

but I get an unexpected ) error in the compiler there. Oddly, a more complex version does work:

foo = (0 for [0...(baz.length)])

Does this rule from the docs only apply to comprehensions that have a range as a source? Is there a cleaner option for this task?

1

There are 1 best solutions below

0
On BEST ANSWER

I actually think that new Array baz.length is the cleaest way to write it. The ambiguity cannot occur as baz.length will always be a number.

I tend to agree with you though that the documentation implies that 0 for baz should work. Possibly worth a bug report?