I'm currently studying javascript from http://eloquentjavascript.net/. I have made a habit of going through the given exercises before moving on to the next chapter to get some practice.
So I've just finished reading chapter 4, and was going through the exercises given at the end of the chapter. Link: http://eloquentjavascript.net/04_data.html
I've just started the first exercise question.
I have successfully completed the first 2 portions of the first exercise question which are:
Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.
Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55.
using the following code:
// Your code 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;
//var numb = 0;
for(numb in numarray)
result += parseInt(numb);
return result;
}
console.log(sum(range(1, 10)));
// → 55 (this is supposed to be the output, and I get this without any problem)
However, there is a bonus task to the same exercise, which seems fairly simple, but I'm failing at it miserably:
As a bonus assignment, modify your range function to take an optional third argument that indicates the “step” value used to build up the array. If no step is given, the array elements go up by increments of one, corresponding to the old behavior. The function call range(1, 10, 2) should return [1, 3, 5, 7, 9]. Make sure it also works with negative step values so that range(5, 2, -1) produces [5, 4, 3, 2].
Here is the code I am using:
// Your code here.
function range(start, end, step)
{
var rangearray = new Array();
end = (end < start) ? end - 1: end + 1;
step = (typeof step === 'undefined') ? 1 : parseInt(step);
var i = 0;
for( i = start ; ((step < 0) ? (i >= end) : (i <= end)) ; (i + step) )
{rangearray.push(i);}
return rangearray;
}
function sum(numarray)
{
var result = 0;
//var numb = 0;
for(numb in numarray)
result += parseInt(numb);
return result;
}
console.log(range(5, 2, -1));
// → [5, 4, 3, 2] (this is supposed to be the output)
When the code runs, I get an alert message saying that the code has been running for more than 2 seconds, and asks if it should be aborted. The same thing happens after 10 seconds. On aborting, the following error is received:
Error: Aborted (line 204 in function tick)
called from line 9 in function range
called from line 25
Any guidance would be much appreciated. :)
line 204 in function tick... you didn't think to post the code around that?inever changes, so, infinite loop ...i + stepshould bei += step