Sum In Range

JavaScript - You have an array of integers, nums, and an array queries, where queries[i] is a pair of indices. Find the sum of the elements in nums from the indices at queries[i][0] to queries[i][1] (inclusive) for each query, then add all of the sums for all the queries together.

by jacobwsmith

JavaScript

/*
You have an array of integers, nums, and an array queries, where queries[i] is a pair of indices. Find the sum of the elements in nums from the indices at queries[i][0] to queries[i][1] (inclusive) for each query, then add all of the sums for all the queries together. Return that number modulo 109 + 7.

Example
For nums = [3, 0, -2, 6, -3, 2] and queries = [[0, 2], [2, 5], [0, 5]], the output should be sumInRange(nums, queries) = 10.
The array of results for queries is [1, 3, 6], so the answer is 1 + 3 + 6 = 10.
*/

// Take Two
function sumInRange(nums, queries) {
  return queries
   	.reduce((total, item) => {
      return total + nums
        .slice(item[0], item[1]+1)
        .reduce((sum, value) => sum + value);
    }, 0)
}

// Take one
/*
function sumInRange(nums, queries) {
  return queries
    .map((item) => {
      return nums
        .filter((ele, index) => index >= item[0] && index <= item[1])
        .reduce((sum, value) => sum + value);
    })
    .reduce((sum, value) => sum + value)
}
*/

/// TESTS ///

/*
nums: [3, 0, -2, 6, -3, 2]
queries: [[0,2],  [2,5], [0,5]]
Output: 10
*/
assertArray(sumInRange([3, 0, -2, 6, -3, 2], [
  [0, 2],
  [2, 5],
  [0, 5]
]), 10);

/*
nums: [34, 19, 21, 5, 1, 10, 26, 46, 33, 10]
queries: [[3,7], [3,4],  [3,7],  [4,5],  [0,5]]
Output: 283
*/
assertArray(sumInRange([34, 19, 21, 5, 1, 10, 26, 46, 33, 10], [
  [3, 7],
  [3, 4],
  [3, 7],
  [4, 5],
  [0, 5]
]), 283);

/*
nums: [1000];
queries: [[0,0]];
Output: 1000;
*/
assertArray(sumInRange([1000], [
  [0, 0]
]), 1000);

function assertArray(actual, expected) {
  if (actual === expected) {
    console.log('passed')
  } else {
    console.log(`FAILED expected \"${expected}\"  but got \"${actual}\"`)
  }
}