Loading article...
The reduce() method executes a reducer function on each element of the array, resulting in a single output value. This polyfill is spec-compliant, handling edge cases like sparse arrays, missing initial values, and proper validation.
if (!Array.prototype.reduce) { Array.prototype.reduce = function(callback, initialValue) { console.log('π§ AOT 1: Validate `this`'); if (this == null) throw new TypeError('Called on null or undefined'); console.log('π§ AOT 2: Validate callback'); if (typeof callback !== 'function') throw new TypeError('Callback is not a function'); console.log('π§ AOT 3: Normalize input'); const array = Object(this); const length = array.length >>> 0; console.log('Array:', array); console.log('Length:', length); let index = 0; let accumulator; if (arguments.length >= 2) { console.log('π§ AOT 4: Using provided initialValue:', initialValue); accumulator = initialValue; } else { console.log('π§ AOT 5: No initialValue, searching for first defined element...'); while (index < length && !(index in array)) { console.log(` - Skipping hole at index ${index}`); index++; } if (index >= length) { console.log('β AOT ERROR: No elements to use as initial accumulator'); throw new TypeError('Reduce of empty array with no initial value'); } accumulator = array[index]; console.log(`β Found initial value at index ${index}:`, accumulator); index++; } console.log('π§ AOT 6: Begin reduction loop'); for (; index < length; index++) { if (index in array) { console.log(`βͺοΈ Applying callback at index ${index}:`, { accumulator, currentValue: array[index], }); accumulator = callback(accumulator, array[index], index, array); console.log(' -> New accumulator:', accumulator); } else { console.log(` - Skipping hole at index ${index}`); } } console.log('β AOT 7: Returning final result:', accumulator); return accumulator; }; }
[1, 2, 3, 4].reduce((a, b) => a + b); // Normal reduce [1, 2, 3, 4].reduce((a, b) => a + b, 10); // With initial value [,,3].reduce((a, b) => a + b, 1); // Sparse array with initial [].reduce((a, b) => a + b); // β Error
Calling:
[1, 2, 3].reduce((a, b) => a + b);
Logs:
π§ AOT 1: Validate `this`
π§ AOT 2: Validate callback
π§ AOT 3: Normalize input
Array: [1, 2, 3]
Length: 3
π§ AOT 5: No initialValue, searching for first defined element...
β
Found initial value at index 0: 1
π§ AOT 6: Begin reduction loop
βͺοΈ Applying callback at index 1: { accumulator: 1, currentValue: 2 }
-> New accumulator: 3
βͺοΈ Applying callback at index 2: { accumulator: 3, currentValue: 3 }
-> New accumulator: 6
β
AOT 7: Returning final result: 6
Test your understanding with 3 quick questions