This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
146. implement Array.prototype.reduce()
Array.prototype.myReduce = function(callback, initialValue) { let accumulator = initialValue === undefined ? undefined : initialValue; for(let i = 0; i < this.length; i++) { if(accumulator !== undefined) { accumulator = callback.call(undefined, accumulator, this[i], i, this); } else { accumulator = this[i]; } } if(accumulator === undefined) { throw new TypeError('Reduce of empty array with no initial value'); } return accumulator;}
Explanation:
- First, we add a new method named
myReduceto the existingArray.prototypemethod. myReduceaccepts a callback function as its first parameter and an optionalinitialValueas its second parameter (it is undefined by default).- Initialize the variable
accumulatorwithinitialValueor undefined, depending on whether aninitialValueis passed or not. - Loop through the array using a for loop.
- If the
accumulatoris not undefined, we call thecallbackfunction and pass in the current valuethis[i]as the second parameter, the current indexias the third parameter, and the original arraythisas the fourth parameter. We set theaccumulatorto the returned value. - If the
accumulatoris undefined, we set it tothis[i]. - If the
accumulatorremains undefined after the loop, we throw an error. - Finally, we return the
accumulator.