Skip to content Skip to sidebar Skip to footer

Turn Coffeescript Loop Using Range Into ES6

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

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

Solution 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.


Post a Comment for "Turn Coffeescript Loop Using Range Into ES6"