settingsAccountsettings
Menusettings

Q: Sub Sum (error handling task with JavaScript)

+3 votes

Write a JS function to sum a range of numeric elements from array. The function takes three parameters – the first is an array, the second is start index and the third is an end index. Both indexes are inclusive. Assume array elements may not be of type Number and cast everything. Implement the following error handling:

  • if the first element is not an array, return NaN
  • if the start index is less than zero, assume it is zero
  • if the end index is outside the bounds of the array, assume it points to the last index of the array

Input / Output:
Your function must take three parameters. As output, return the resulting sum as instructed.

Examples:

Sample Input:

subsum([10, 20, 30, 40, 50, 60], 3, 300)
 
Output:

150


Sample Input:

subsum([1.1, 2.2, 3.3, 4.4, 5.5], -3, 1)
 
Output:

3.3


Sample Input:

subsum([10, 'twenty', 30, 40], 0, 2)
 
Output:

NaN


Sample Input:

subsum([], 1, 2)
 
Output:

0


Sample Input:

subsum('text', 0, 2)  
 
Output:

NaN

asked in JavaScript category by user icabe

1 Answer

+1 vote

My solution:

function subSum(arr, startIndex, endIndex) {
    if (!Array.isArray(arr))
        return NaN;
    if (startIndex < 0)
        startIndex = 0;
    if (endIndex > arr.length - 1)
        endIndex = arr.length - 1;
    let sum = 0;
    for (let i = startIndex; i <= endIndex; i++)
        sum += Number(arr[i]);
    return sum;
}

console.log(subSum([10, 20, 30, 40, 50, 60], 1, 20));
console.log(subSum([10, 20, 30, 40, 50, 60], -1, 4));
console.log(subSum([10, 20, 30, 40, 50, 60], -1, 20));
console.log(subSum(["Pesho", 20, 30, 40, 50, 60], 3, 4));
console.log(subSum([], 3, 4));
console.log(subSum({}, 3, 4));

 

answered by user ak47seo
...