Having googled for it I found two solutions:
Here is a range
function which takes start
, end
, and a step
parameter. It returns an array starting a from start
upto (but excluding) the end
number with increments of size step
.
const range = (start, end, step) => {
return Array.from(Array.from(Array(Math.ceil((end-start)/step)).keys()), x => start+ x*step);
}
console.log(range(1, 10, 1));
//[1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(range(0, 9, 3));
//[0, 3, 6]
console.log(range(10, 30, 5));
//[10, 15, 20, 25]
Taking a step further, if you want a range that includes the end
as well.
const inclusiveRange = (start, end, step) => {
return Array.from(Array.from(Array(Math.ceil((end-start+1)/step)).keys()), x => start+ x*step);
}
console.log(inclusiveRange(1, 10, 1));
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(inclusiveRange(0, 9, 3));
// [0, 3, 6, 9]
console.log(inclusiveRange(10, 30, 5));
//[10, 15, 20, 25, 30]