Sum is to be calculated for the numbers in between the array's max and min value JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function, say sumBetween() that takes in an array [a,b] of two elements and returns the sum of all the elements between a and b including a and b.

For example −

[4, 7] = 4+5+6+7 = 22
[10, 6] = 10+9+8+7+6 = 40

Let’s write the code for this function −

Example

const arr = [10, 60];
const sumUpto = (n) => (n*(n+1))/2;
const sumBetween = (array) => {
   if(array.length !== 2){
      return -1;
   }
   const [a, b] = array;
   return sumUpto(Math.max(a, b)) - sumUpto(Math.min(a, b)) + Math.min(a,b);
};
console.log(sumBetween(arr));
console.log(sumBetween([4, 9]));

Output

The output in the console will be −

1785
39
raja
Published on 20-Aug-2020 09:56:11
Advertisements