DEV Community

Discussion on: 1 line of code: How to create a range array

Collapse
 
pengeszikra profile image
Peter Vivo • Edited
const makeRange = (a, b, sign = Math.sign(b - a)) => 
  Array(Math.abs(b - a + sign))
    .fill()
    .map((_, i) => a + sign * i)
  ;

// makeRange(3, -4) -> [3, 2, 1, 0, -1, -2, -3, -4]
Enter fullscreen mode Exit fullscreen mode

Maybe can write in single line.

Collapse
 
martinkr profile image
Martin Krause

Hi,
thank you for your contribution.
Nice code - I'll set up a benchmark.and compare all suggestions so we can find the fastest one.
Cheers!

Cheers!

Collapse
 
martinkr profile image
Martin Krause

Check the Benchmark). I updated the article and the code with your solution.