Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
range.js
const range = function* (stop = 0, step = 1) {
const shouldStop = (n)=>stop >= 0 ? (n < stop) : (n > stop);
const interval = (n)=>stop >= 0 ? n + step : n - step;
let itr = function*() {
let i = 0;
while (shouldStop(i)) {
yield i;
i = interval(i);
}
};
itr[Symbol.iterator] = itr;
yield* itr;
};
for (let i of range(5))
console.log(i);
for (let i of range(-5))
console.log(i);
[...range(5)]
@jeffposnick

This comment has been minimized.

Copy link

commented Jul 11, 2017

How about:

function* range(start, stop, step = 1) {
  let counter = start;
  let direction = stop > 0;
  while (counter < stop === direction && counter !== stop) {
    yield counter;
    counter += step;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.