Currently, I am delving into the world of JavaScript by exploring . I find it beneficial to tackle the exercises provided before progressing to the next chapter as a way to practice.
After completing chapter 4 and reviewing the exercises found at the end of the chapter, you can access them via this link:
I have just started working on the first exercise question.
I have managed to successfully complete the initial two sections of the first exercise question which are:
Create a range function that accepts start and end parameters and returns an array with all numbers between start and end inclusive.
Next, create a sum function that takes an array of numbers and calculates the total sum. Run the previous program to verify if it indeed returns 55.
The code I used looks like this:
// Your implementation here.
function range(start, end)
{
var rangearray = new Array();
for(var i = start; (i <= end + 1); i++)
rangearray.push(i);
return rangearray;
}
function sum(numarray)
{
var result = 0;
for(var numb in numarray)
result += parseInt(numarray[numb]);
return result;
}
console.log(sum(range(1, 10)));
// → 55 (desired output achieved without difficulty)
However, I am struggling with the bonus task associated with the same exercise, even though it seems relatively straightforward:
As an additional assignment, modify your range function to accept an optional third argument indicating the step value to build the array. If no step is given, the elements increase by one increment as per the old behavior. The function call range(1, 10, 2) should produce [1, 3, 5, 7, 9]. Ensure it functions properly with negative step values such as range(5, 2, -1) resulting in [5, 4, 3, 2].
This is the code snippet I have been using:
// Your implementation here.
function range(start, end, step)
{
var rangearray = new Array();
end = (end < start) ? end - 1 : end + 1;
step = (typeof step === 'undefined') ? 1 : parseInt(step);
for(var i = start; ((step < 0) ? (i >= end) : (i <= end)); (i += step))
{
rangearray.push(i);
}
return rangearray;
}
function sum(numarray)
{
var result = 0;
for(var numb in numarray)
result += parseInt(numarray[numb]);
return result;
}
console.log(range(5, 2, -1));
// → [5, 4, 3, 2] (expected output)
Upon running the code, I encountered a warning stating that it has taken longer than 2 seconds to execute, with an option to abort. This message repeats after 10 seconds, leading to the following error upon abortion:
Error: Aborted (line 204 in function tick)
Called from line 9 in function range
Called from line 25
Any advice or assistance on resolving this issue would be greatly appreciated. :)