Detailed explanation of JavaScript's Array. reduce source code interpretation
- 2021-09-12 00:01:30
- OfStack
Preface
The reduce (...) method executes one reducer function provided by you on each element in the array (executed in ascending order), summarizing its results into a single return value (cumulative effect)
This method takes two parameters: callback (...) (required) and initialValue (optional).
callback (...) accepts four parameters: Accumulator (acc) (accumulator), Current Value (cur) (current value), Current Index (idx) (current index), Source Array (src) (source array).
Note:
1. callback (...) 1 generally requires a return value
2. The original array will not be changed
Realization thought
1. Get the initial accumulated value first (divided into two cases: initialValue is provided but initialValue is not provided)
2. Traverse the array and execute callback (...)
3. Return the cumulative value
Source code implementation
Array.prototype.myReduce = function(callback, initialValue) {
if(this === null) {
throw new TypeError( 'Array.prototype.reduce called on null or undefined' );
}
if (typeof callback !== 'function') {
throw new TypeError( callback + ' is not a function');
}
const O = Object(this);
const lenValue = O.length;
const len = lenValue >>> 0;
if(len === 0 && !initialValue) {
throw new TypeError('the array contains no elements and initialValue is not provided');
}
let k = 0;
let accumulator;
// Divide into two situations to get accumulator
// Available initialValue accumulator=initialValue
// Not provided initialValue accumulator= The number of the array 1 Valid elements
if(initialValue) {
accumulator = initialValue;
} else {
let kPressent = false;
while(!kPressent && k < len) {
const pK = String(k);
kPressent = O.hasOwnProperty(pK);
if(kPressent) {
accumulator = O[pK];
};
k++;
}
if(!kPressent) {
throw new TypeError('the array contains error elements');
}
}
// When accumulator=initialValue Hour k=0
// accumulator= The number of the array 1 Valid elements k=1
while(k < len) {
if(k in O) {
// callback1 You need to return a value
accumulator = callback(accumulator, O[k], k, O);
}
k++;
}
return accumulator;
}
let r = [1,2,3].myReduce(function (prevValue, currentValue, currentIndex, array) {
return prevValue + currentValue;
}, 22);
console.log(r); // 28
Reference link:
reduce-mdn
Official norm