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
myReduce
to the existingArray.prototype
method. myReduce
accepts a callback function as its first parameter and an optionalinitialValue
as its second parameter (it is undefined by default).- Initialize the variable
accumulator
withinitialValue
or undefined, depending on whether aninitialValue
is passed or not. - Loop through the array using a for loop.
- If the
accumulator
is not undefined, we call thecallback
function and pass in the current valuethis[i]
as the second parameter, the current indexi
as the third parameter, and the original arraythis
as the fourth parameter. We set theaccumulator
to the returned value. - If the
accumulator
is undefined, we set it tothis[i]
. - If the
accumulator
remains undefined after the loop, we throw an error. - Finally, we return the
accumulator
.