Create a range function in JavaScript
The following code will return an array of consecutive integers, starting at zero and going up to 4:
[...Array(5).keys()]
// Output: [0,1,2,3,4]
This works invoking the `Array` constructor function with an argument of 5. This creates an array of length 5, with every element having a value of `undefined`.
Array(5)
// Output: [undefined,undefined,undefined,undefined,undefined]
The `keys` method returns an array iterator object containing the index of each element in the array. We can then the spread operator to convert this back into an array:
[...Array(5).keys()]
// Output: [0,1,2,3,4]
We can write a function to generalise this so that it returns an array of consecutive integers, starting at zero and length n:
const consecutiveIntegers = n => [...Array(n).keys()]
consecutiveIntegers(8)
// Output: [0,1,2,3,4,5,6,7]
Creating the Range function in JavaScript
Python has a built-in `range` function and Ruby has an operator for creating ranges. They produce a range of consecutive integers from a to b. We can use the code above to create a `range` function in JavaScript:
const range = (start,end) => end
? [...Array(end - start).keys()].map(n => n + start)
: [...Array(start).keys()]
range(3)
// Output: [0,1,2]
range(4,9)
// Output: [4,5,6,7,8]
This function starts by checking to see if a second argument has been provided. If it hasn’t then the default start value is zero and we use the same code as before. Otherwise, we subtract the 'end' and 'start' arguments to get the length of the array and then use the 'map' function to add the 'start' value to each element of the array.