Advertisement
TZinovieva

Sub Sum JS Advanced

Oct 3rd, 2023
662
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.  
  6.     if (arr.length === 0) {
  7.         return 0;
  8.     }
  9.  
  10.     startIndex = Math.max(startIndex, 0);
  11.  
  12.     endIndex = Math.min(endIndex, arr.length - 1);
  13.  
  14.     let sum = 0;
  15.  
  16.     for (let i = startIndex; i <= endIndex; i++) {
  17.         if (typeof arr[i] !== "number") {
  18.             return NaN;
  19.         }
  20.         sum += arr[i];
  21.     }
  22.  
  23.     return sum;
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement