0

Disclaimer: I don't know Coffeescript and, although I appreciate it has contributed towards the ES6 spec, I can't wait to see the back it.

This Coffeescript loop (wrote by someone else)

if @props.total>1
  for page in [1..@props.total]
    active = (page is +@props.current)

is, according to js2coffee, equivalent to this JS

var active, i, page, ref;

if (this.props.total > 1) {
  for (page = i = 1, ref = this.props.total; 1 <= ref ? i <= ref : i >= ref; page = 1 <= ref ? ++i : --i) {
    active = page === +this.props.current;
  }
}

Now I would like to use a for..of loop to shorten that JS, but I can't figure out how.

I've tried to implement this idea(the generator function bit at the bottom), but I can't get it right.

My question is: Is there a way of making ranges in ES6?

U r s u s
  • 6,680
  • 12
  • 50
  • 88
  • The `function* range` from the linked article should work (and no, there aren't many other ways to implement ranges). Please show us the exact code you tried. – Bergi Sep 30 '16 at 11:24
  • A simple `for (let page = 1; page < this.props.total; page++)` loop would probably be the easiest solution. No need to use a `for of` loop here, even if that's the equivalent to Coffeescript's `for in`. – Bergi Sep 30 '16 at 11:27
  • …and given that you set `active` to the last comparison anyway, you could omit the loop completely :-) – Bergi Sep 30 '16 at 11:27
  • wait, wat? your last comment threw me a bit. – U r s u s Sep 30 '16 at 11:29
  • I guess that you actually have a different loop body that does more than assigning the `active` variable, but the snippet you've shown us could be reduced to `if (this.props.total > 1) active = this.props.total === +this.props.current;` – Bergi Sep 30 '16 at 11:32
  • Sure. Let me see if I can get the generator code I have to make sense and post it. – U r s u s Sep 30 '16 at 11:34
  • Any update? Did you get it to work? – Bergi Sep 30 '16 at 14:02
  • Nope. Still struggling to find a reasonable way of rendering that. – U r s u s Sep 30 '16 at 15:50

2 Answers2

2

The generator solution you are looking for would be

function* range(i, end=Infinity) {
    while (i <= end) {
        yield i++;
    }
}

// if (this.props.total > 1) - implicitly done by `range`
for (let page of range(1, this.props.total) {
    active = page === +this.props.current;
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

For generating any range of sequential integers of length k starting at n in JavaScript the following should work:

Array.apply(null, Array(k)).map((x, i) => i + n);

While not quite the same as the coffeescript range functionality, its probably close enough for most uses. Also despite being significantly more verbose has one decided advantage: you don't have to remember which of .. and ... is exclusive and which is inclusive.

Jared Smith
  • 19,721
  • 5
  • 45
  • 83