Eloquent JavaScript - Chapter 4 - Data Structures Objects and Arrays (Notes)

*Exercises

The sum of a range

function range(start, end, step) {
// If no optional step, set step to 1.
if (step == null) step = 1;

// Initialize the array that will eventually be returned.
var array = [];

// If the range is increasing, continue pushing i to the
// array and incrementing i by step until i is greater than
// end, then stop.
if (step > 0) {
for (var i = start; i <= end; i += step)
array.push(i);
// If the range is decreasing, continue pushing i to the
// array until i is less than end, then stop.
// Remember i will get smaller because step is negative.
} else {
for (var i = start; i >= end; i += step)
array.push(i);
}
// Return the result
return array;
}

function sum(array) {
// Set total to start at 0.
var total = 0;
// Go through each item in the array and add it to result.
for (var i = 0; i < array.length; i++)
total += array[i];
// Return result.
return total;
}

console.log(sum(range(1, 10)));
// → 55
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]

×Reversing an array

/*
function reverseArrayInPlace(array) {
for (var i = 0; i < Math.floor(array.length / 2); i++) {
var old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
*/


function reverseArrayInPlace(array) {
var b = array.length;
for (var i = 0; i < --b; i++) {
var swap = array[i];
array[i] = array[b];
array[b] = swap;
}
return array;
}

function reverseArray(array) {
var output = [];

for (i = array.length - 1; i >= 0 ; i--)
{
output.push(array[i]);
}

return output;
}

console.log(reverseArray(["A", "B", "C"]));
// → ["C", "B", "A"];
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]