re: How to create range in Javascript VIEW POST

FULL DISCUSSION
 

I liked your recursive generator. How about something like this:

Number.prototype.to = function* (end) {
  const start = this;
  const step = end > start ? 1 : -1;
  const fn = function* (n) {
    let next = start + step * n;
    yield next;
    if (next === end) return;
    yield* fn(n + 1);
  };
  yield start;
  yield* fn(1);   
}

const asc = [...(1).to(5)];
const dsc = [...(5).to(1)];

console.log(asc); // [1, 2, 3, 4, 5]
console.log(dsc); // [5, 4, 3, 2, 1]
 
code of conduct - report abuse