The sum of a range
The introduction of this book alluded to the following as a nice way to compute
the sum of a range of numbers:
console.log(sum(range(1, 10)));
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 example program and see whether it does
indeed return 55.
As a bonus assignment, modify your range function to take an optional third
argument that indicates the “step” value used when building the array. If no
step is given, the 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] .
function range(start, end, step){
var output = [];
if (step == undefined || step == null || step == 0)
step = 1;
console.log("The step increment by default will be set to one.");
if (start>end && step<0){
for(i=start;i>=end;i=i+step){
output.push(i);
}
} else if (start<end && step>0){
for (i=start; i<=end; i=i+step){
output.push(i);
}
} else {
alert("Invalid range or step increment/decrement.");
}
return output;
}
function sum(numOutput){
var outputTotal = 0;
numbers = numOutput.length;
for(var i = 0; i < numbers; i++){
outputTotal += numOutput[i];
}
return outputTotal;
}
console.log(range(1,19));
console.log(range(21,3,-2));
console.log(sum(range(1,75)));
Reversing an array
Arrays have a reverse method that changes the array by inverting the order in
which its elements appear. For this exercise, write two functions, reverseArray
and reverseArrayInPlace . The first, reverseArray , takes an array as argument
and produces a new array that has the same elements in the inverse order. The
second, reverseArrayInPlace , does what the reverse method does: it modifies
the array given as argument by reversing its elements. Neither may use the
standard reverse method.
Thinking back to the notes about side effects and pure functions in the
previous chapter, which variant do you expect to be useful in more situations?
Which one runs faster?
function reverseArray(a){
var output = [];
for(i=0;i < a.length;i++){
var entry = a[i];
output.unshift(entry);
}
return output;
};
function reverseArrayInPlace(arg){
var result;
for(i=0; i<arg.length/2;i++){
result = arg[i];
arg[i] = arg[arg.length - 1 - i];
arg[arg.length - 1 - i] = result;
}
}
console.log(reverseArray([“Coffee”,“Pineapple”,“Apricot”]))
var coding = [3,1,4,9,5];
reverseArrayInPlace(coding);
console.log(coding);