In the below example, we create a function that's responsible for looping through an array. At each traversal, if we've reached the end of the array, we return x. Otherwise, we call the function again with i
incremented, and with x
added with the value of the array at index i
.
function sum(arr, i = 0, x = 0) {
return i === arr.length
? x
: sum(arr, i + 1, x + arr[i]);
}
console.log(
sum([1,2,3])
);
// 6
If we want to get the sum of all possible subsets, then we can add another call to be returned. For the example below, it would be sumOfSubsets(arr, i + 1, x)
. This call excludes the current item at index i
of arr
from being counted in the summation. When we do this recursively, we are able to traverse all subsets in this way.
function sumOfSubsets(arr, i = 0, x = 0) {
return i === arr.length
? x
: sumOfSubsets(arr, i + 1, x + arr[i]) + sumOfSubsets(arr, i + 1, x);
}
console.log(
sumOfSubsets([1,2,3])
);
// 24
// 1 + 2 + 3 = 6
// 1 + 2 = 3
// 2 + 3 = 5
// 1 + 3 = 4
// 1 = 1
// 2 = 2
// 3 = 3
// = 24