I am writing a range function that takes two arguments (start, and end). It will return an array containing all the numbers from start up to end.
I am making the sum of the range function by a few steps.
Step 1:
Making the range function called myRange()
with two parameters. Inside the function body, initialize an array to store numbers and it will return a numbers of array.
Now, I am using the for loop to iterate the number range from start to end and using the push method to put value to the array each iteration.
function myRange(start, end) {
let arr = [];
for(let i = start; i <= end; i++) {
arr.push(i)
}
return arr;
}
console.log(myRange(1, 10));
I have input the number 1, and 10 as arguments to myRange(1, 10)
function. The output is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.
But, the problem will occur if someone passes arguments large to small numbers.
Step 2:
Probably, it will be best to write two separate loops - one for counting up and one for counting down. Also, I have to check whether the start
parameter value is bigger or smaller. Then the loop will run by following the condition.
function myRange(start, end) {
let arr = [];
if (start <= end) {
for(let i = start; i <= end; i++) {
arr.push(i)
}
} else if (start >= end) {
for (let i = start; i >= end; i--) {
arr.push(i);
}
}
return arr;
}
console.log(myRange(1, 10)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(myRange(5, 2)); // [5, 4, 3, 2]
I have called myRange()
function two times and console them with passed values - one smaller to bigger and one bigger to smaller.
Step 3:
Now, I am creating the sum function called mySum()
and passed a parameter. Initialize the sum variable to return the result. I am using for loop for the summation of the values of the previous one to the current one in each iteration.
function mySum(val) {
let sum = 0;
for (let i = 0; i < val.length; i++) {
sum += val[i];
}
return sum;
}
console.log(mySum(myRange(1, 10))); // 55
console.log(mySum(myRange(5, 2))); // 14
After the summation the results are 55
for the first range and 14
for the second range.
That's it!
Please share your valuable feedback and suggest to me if I doing wrong. Your feedback/suggestions will inspire me to learn.