I am trying to write a function that returns a list of integers from a ‘start’ value (inclusive) to a ‘stop’ value (exclusive) and am given the ‘step’ (or number to increment by…).
The function is supposed to be able to handle different amount of arguments passed in. I believe I have the function most of the way completed but I seem to be getting an infinite loop and am unsure why or how to proceed.
Here is the code I have written so far…
function range(start, stop, step) {
if (arguments.length===1) {
start = 0;
stop = arguments[0];
step = 1;
} else if (arguments.length===2) {
start = arguments[0];
stop = arguments[1];
step = 1;
} else if (arguments.length===3) {
start = arguments[0];
stop = arguments[1];
step = arguments[2];
}
// define result array
let result = [];
// create a for-loop
for (start; start < stop; start + step) {
result.push(start);
}
return result;
}
And here are some example calls and their expected outputs…
range(10); -> [0,1,2,3,4,5,6,7,8,9]
range(1,11); -> [1,2,3,4,5,6,7,8,9,10]
range(0,30,5); -> [0,5,10,15,20,25]
range(0,-10,-1); -> [0,-1,-2,-3,-4,-5,-6,-7,-8,-9]
The function is also supposed to be able to do negative ranges with negative ‘step’ values as well.
Could someone explain to me why I seem to be getting an infinite loop?