DEV Community

Discussion on: How to create range in Javascript

Collapse
josefrichter profile image
Josef Richter

The recursive one is really nice. Can be shortened to:

const range = (s, e) => e > s ? [s, ...range(s + 1, e)] : [s];
Enter fullscreen mode Exit fullscreen mode

Also this is another approach, + easier to handle descending sequences too:

const range = (s,e) => e > s ? Array(e - s + 1).fill(0).map((x, y) => y + s) : Array(s - e + 1).fill(0).map((x, y) => - y + s);
Enter fullscreen mode Exit fullscreen mode