2

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?

Community
  • 1
  • 1
Jwashton
  • 302
  • 1
  • 11
  • 1
    I personally __hate__ this style of _cute, magical_ code. At first pass, I have no idea what your code is supposed to do. On the other hand, the _deliberate and obvious_ version, `foo = []; baz.forEach -> foo.push 0` is crystal clear, even if you maintain the strict paren-phobia encouraged by CS fans. – Evan Davis Jun 23 '15 at 15:33

1 Answers1

0

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?

Cliff Stanford
  • 614
  • 7
  • 11