DEV Community

Discussion on: How to create range in Javascript

Collapse
 
johnboy5358 profile image
John

Yes, excellent solution.

This, slimmed down, version also works...

const range = (start, end, length = end - start) =>
  Array.from({ length }, (_, i) => start + i)

Collapse
 
kerafyrm02 profile image
kerafyrm02 • Edited

const range = (start, end) => Array.from({length: end}, (_, i) => start + 1);

Thread Thread
 
johnboy5358 profile image
John

Sorry kerafyrm02, but that does not produce a range.

If I run range with range(1,50) I get [2,2,2,2,2,2,2,2,...]

const range = (start, end) => Array.from({length: end}, (_, i) => start + 1); console.log(range(0,20))
Thread Thread
 
kerafyrm02 profile image
kerafyrm02 • Edited

let r = (s, e) => Array.from('x'.repeat(e - s), (_, i) => s + i);

Ok here ya go... even shorter. :D

Thread Thread
 
johnboy5358 profile image
John

Rock, paper, scissors... 68 chars, you've nailed it!

Thread Thread
 
kerafyrm02 profile image
kerafyrm02

lol., made range to r.. so even shorter :D

Thread Thread
 
johnboy5358 profile image
John • Edited

Trust me to bump into a js golfer.

Next you'll be telling me that you're dropping the let keyword and just leaving r on the global object!!

Thread Thread
 
ycmjason profile image
YCM Jason

haha! nice solution John!

Thread Thread
 
johnboy5358 profile image
John

Well, thank you so much for saying!

Collapse
 
mbrookes profile image
Matt

Almost.

Try:

const range = (start, end, length = end - start + 1) =>
  Array.from({ length }, (_, i) => start + i)
Enter fullscreen mode Exit fullscreen mode
> range(0,2)
[ 0, 1, 2 ]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
acatalfano profile image
Adam Catalfano

as satisfying as this is, you're exposing a third argument that anyone can override. In a modern tech stack, this code is hesitantly admissible only if you can guarantee that absolutely no one can set length to be anything but end - start, otherwise you need to invest in a much more complex testing framework, likely outweighing the expense of adding a second line to this function.