I am asked to do the following:
-
Write a range function that takes 3 arguments: start, end and step. Return an array containing all the numbers from start to end.
-
Step indicates the “step” value used to build up the array. If no step is given, the array elements go up by increments of one.
-
Write a sum function that takes an array of numbers and returns the sum of these numbers.
-
Below is my code, I think I have tackled the sum function portion, the range function portion is not working out:
//Range Function Portion
function range(start, end, step) {
var arr = [];
if (step>0) {
for(var i = start; i <= end; i=i + step){
arr.push(i);
}
}else {
for(var i = end; i <= start; i++){
arr.push(i);
}
}
return arr;
}
//Sum Function Portion
function sum(arr) {
var sum = 0;
// Write code here
for(var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
//I am supposed to output the following:
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