In this challenge, you will build a function that creates an array for a given start, end, and step parameter.
- The function takes three integer parameters: start, end, and step.
- The function should return an array of numbers from start to end, counting by step.
The function checks for incorrect parameters by ensuring that;
- start, end, or step are defined
- start is not greater than end
- step is greater than zero
If any of these parameters are not met, the function should return an empty array [].
My code:
function range (start, end, step) {
const result = [];
for (let i = start; i <= end; i += step) {
result.push(i);
}
return result;
}
console.log(range(0, 10, 2));
RangeError: Invalid array length
>Solution :
You forgot to do the validations described.
While doing the validations, you can use early return to get a code with more readability.
start, end, or step are defined
if (start === undefined || end === undefined || step === undefined) {
return []
}
start is not greater than end
if (start > end) {
return []
}
step is greater than zero
if (step <= 0) {
return []
}
Final function:
function range (start, end, step) {
if (start === undefined || end === undefined || step === undefined) {
return []
}
if (start > end) {
return []
}
if (step <= 0) {
return []
}
const result = [];
for (let i = start; i <= end; i += step) {
result.push(i);
}
return result;
}