DEV Community

Discussion on: How to create range in Javascript

Collapse
 
johnboy5358 profile image
John • Edited

It rather depends, Jason, on what you mean by cooler.

If you only needed range to handle approx. 6000 iterations then I think a recursive range function is pretty cool, but slow:

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

But, if you need a much bigger range and fast executuion then do something like this:

const range = (s=0,e=10,r=[]) =>
  {while(e >= s){ r.push(s); (e>=s)? s++ : s--; } return r }
Enter fullscreen mode Exit fullscreen mode

And if you don't like the arrow function, then it's easy to convert to a standard es5 style function.