DEV Community

Discussion on: How to create range in Javascript

Collapse
 
nycdude777 profile image
Rick Ellis • Edited

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]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ycmjason profile image
YCM Jason

Haha! I like this idea!

Collapse
 
pinksynth profile image
Sammy Taylor

This is great, I wish this would make its way into the spec.