Turn Coffeescript loop using range into ES6

2019-09-15 01:45发布

问题:

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?

回答1:

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


回答2:

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.