Implement a Polyfill for Array.prototype.reduce
viaLeetCode
Problem Write a spec-faithful polyfill for Array.prototype.reduce.
Input / Output
- myReduce(callback, initialValue?) on an array; callback(accumulator, current, index, array).
Constraints
- Must match native semantics: no initialValue → accumulator seeds from the FIRST PRESENT element and iteration starts at the next; empty array with no initialValue → TypeError; holes in sparse arrays are skipped; callback must not be called for the seed element.
Example
- [1,2,3].myReduce((a,b) => a+b) → 6 (callback runs twice, not three times).
- [].myReduce(f) → TypeError; [].myReduce(f, 0) → 0 (callback never runs).
Expected approach
- Attach via Array.prototype.myReduce = function(cb, init) { … }: validate cb is callable; O = Object(this), len = O.length >>> 0; k = 0; if init absent, advance k past holes to find the seed (throw if none); loop k < len calling cb only where k in O (hole skipping via the in check); return accumulator. The evaluated details: the two seeding modes, the TypeError case,
thishandling (works on array-likes via call), and NOT using arrow functions for the method (needs dynamic this). Follow-ons: reduceRight (mirror), map/filter polyfills via reduce.
asked …