Skip to content

for x in y by -1 #1208

Closed
Closed
@TrevorBurnham

Description

Someone recently tweeted their frustration at for loops in CoffeeScript, and particularly this nasty case:

console.log x for x in y by -1

is an infinite loop for any array y, as this output makes clear:

for (_i = 0, _len = y.length; _i < _len; _i += -1) {
  x = y[_i];
  console.log(x);
}

As you can see, the index is set to 0, then counts down from there until it hits y.length.

I understand the historical reasons for this: by is only intended to be used in conjunction with the for...in range syntax. So the easy fix would be to simply throw a syntax error when by is used with the for...in arr syntax.

But we can do better by supporting for...in arr by step, where step is a constant:

  1. If step is a positive integer value, keep the current behavior. It's fine.
  2. If step is a negative integer value, set the initial index to y.length - 1 instead of to 0 and make the loop criterion _i >= 0; there's no need for _len.
  3. If step is any other value (e.g. 0 or 0.2), throw a syntax error.

Variable step values should also probably be supported, though I'm not sure how zero/non-integer values should be handled; maybe the best approach is to just assume that the user knows what they're doing, in which case the compilation can be to something like

for (_len = y.length; _i = step > 0 ? 0 : len - 1; step > 0 ? _i < _len : _i >= 0; _i += step) {
  x = y[_i];
  console.log(x);
}

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions