The first attempt by following the pattern shown in the problem description:
type Fn = (accum: number, curr: number) => number
function reduce(nums: number[], fn: Fn, init: number): number {
if(nums.length === 0) return init;
let accum = init;
for(let i = 0; i < nums.length ; i+= 1){
accum = fn(accum, nums[i]);
}
return accum;
};
After reviewing the top-ranked solution, I realized that the early return if(nums.length === 0) return init;
is not necessary. The reason is that I have assigned the initial value init
to accum
with let accum = init;
, and it will be returned even if the length of the array nums
is 0.
Thus, a better solution should be:
type Fn = (accum: number, curr: number) => number
function reduce(nums: number[], fn: Fn, init: number): number {
let accum = init;
for(let i = 0; i < nums.length ; i+= 1){
accum = fn(accum, nums[i]);
}
return accum;
};
Top comments (0)