Topic Description

Given an integer array nums, a reduction function fn, and an initial value init, implement a reduce function that sequentially executes the fn function on each element in the array, using the return value from the previous execution as the input for the next execution.

Specifically, it works like this: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... until all elements in the array have been processed. Finally, return the final value of val.

If the array length is 0, the function should return init.

Do not use JavaScript's built-in Array.reduce method to solve this problem.

// Example 1
Input: 
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr; }
init = 0
Output: 10
Explanation:
The initial value is init=0.
(0) + nums[0] = 1
(1) + nums[1] = 3
(3) + nums[2] = 6
(6) + nums[3] = 10
So the final result is 10.

// Example 2
Input: 
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr * curr; }
init = 100
Output: 130
Explanation:
The initial value is init=100.
(100) + nums[0] * nums[0] = 101
(101) + nums[1] * nums[1] = 105
(105) + nums[2] * nums[2] = 114
(114) + nums[3] * nums[3] = 130
So the final result is 130.

Answer

function reduce(nums, fn, init){
	let total = init
	for(const num of nums){
		total = fn(total,num)
	}
	return total
}