Implement a range function in JavaScript

I like to define a simple range function in my JavaScript projects, in order to easily adopt a functional approach when I need to work with integer intervals:

1
2
3
4
5
6
7
function range(start, end) {
const right = end || start
const left = end && start || 0
return Array.from({length: right - left}, (x, i) => left + i)
// Alternative implementation:
// return Array(right - left).fill(0).map((x, i) => left + i)
}

Basic usage:

1
2
3
4
5
6
7
8
range(0, 10)
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(5, 10)
// [5, 6, 7, 8, 9]

range(7)
// [0, 1, 2, 3, 4, 5, 6]