Given an integer array nums, a reducer function fn, and an initial value init, return a reduced array.
A reduced array is created by applying the following operation: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... until every element in the array has been processed. The final value of val is returned.
If the length of the array is 0, it should return init.
Please solve it without using the built-in Array.reduce method.
var reduce = function(nums, fn, init) {
}
Example 1:
Input:
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr; }
init = 0
Output: 10
Example 2:
Input:
nums = [1,2,3,4]
fn = function sum(accum, curr) { return accum + curr * curr; }
init = 100
Output: 130
Example 3:
Input:
nums = []
fn = function sum(accum, curr) { return 0; }
init = 25
Output: 25
開始有點煩了,但跟昨天的有點類似
本來還寫了 if 來判斷,但看了別人的解法,覺得多此一舉,改為以下
var reduce = function(nums, fn, init) {
let count = init;
for (let i = 0; i < nums.length; i++) {
count = fn(count, nums[i]);
}
return count;
};