Hello everyone, here is my post. I found this code in GitHub.
The sum of a range.
// range function
function range( start, end, increment ) {
// create the result array
var result = [];
// test to see if we have an increment, otherwise set it to 1
if ( increment == undefined )
increment = 1;
// calculate the number of times to loop (this is because you might be going
// up or down with your increment)
numLoops = Math.abs( (end - start)/ increment ) + 1 ;
// loop that many times
for ( var i = 0; i < numLoops; i ++ ) {
// add (push) the value of start to the array
result.push( start );
// increment the value of start
start += increment;
}
// return the array with all the things in it
return result;
}
function sum( numArray ) {
// set a variable to hold the sum
var arrayTotal = 0;
// see how many numbers are in the array
numLoops = numArray.length;
// loop that many times
for ( var i = 0; i < numLoops; i ++ ) {
// add the number at that index to the sum
arrayTotal += numArray[i];
}
// return the sum
return arrayTotal;
}
console.log(range(1, 10));
// β [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// β [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// β 55
Reversing the array is
function reverseArray(array) {
result = [];
for (let item of array) {
result.unshift(item);
}
return result;
}
function reverseArrayInPlace(array) {
let len = array.length;
for (let i = 0; i < Math.floor(len/2); i++) {
console.log(i, len-i-1, array[i], array[len-i-1], array);
let swap = array[i];
array[i] = array[len-i-1];
array[len-i-1] = swap;
}
return array;
}
console.log(reverseArray([βAβ, βBβ, βCβ]));
// β [βCβ, βBβ, βAβ];
let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// β [5, 4, 3, 2, 1]
let arrayValue2 = [1, 2, 3, 4];
reverseArrayInPlace(arrayValue2);
console.log(arrayValue2);
// β [4, 3, 2, 1]