Skip to content

Instantly share code, notes, and snippets.

@PaulKinlan
Last active August 2, 2017 23:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PaulKinlan/405e92cc9d328222f493a79305484a86 to your computer and use it in GitHub Desktop.
Save PaulKinlan/405e92cc9d328222f493a79305484a86 to your computer and use it in GitHub Desktop.
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
Copy link

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