Advertisement
kstoyanov

01. Sub Sum

Oct 26th, 2020
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function subSum(arr, startIndex, endIndex) {
  2.   if (!Array.isArray(arr)) {
  3.     return NaN;
  4.   }
  5.   if (Number(startIndex) < 0) {
  6.     startIndex = 0;
  7.   }
  8.   if (Number(endIndex) > arr.length - 1) {
  9.     endIndex = Number(arr.length - 1);
  10.   }
  11.  
  12.   const inputArr = arr.map(Number).slice(startIndex, endIndex + 1);
  13.  
  14.   const isNan = inputArr.some((el) => isNaN(el));
  15.  
  16.   if (!isNan) {
  17.     let sum = 0;
  18.  
  19.     for (let i = 0; i < inputArr.length; i++) {
  20.       sum += inputArr[i];
  21.     }
  22.  
  23.     if (sum % 1 === 0) {
  24.       return Number(sum);
  25.     }
  26.     return Number(sum.toFixed(1));
  27.   }
  28.   return NaN;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement