This is the fifth day of my participation in the August Wen Challenge.More challenges in August
theme: juejin
The problem
Implement a array.reduce() by hand;
Goals to achieve: Implement reduce on a prototype chain that can be called directly, such as array.myReduce();
Understand the array. The reduce ()
Accepts two parameters, a function that processes the data and an initial value.
Receive a function of processing data, can receive four parameters (total, curValue curIndex, array);
- Total (the value returned from the last call to the callback, or the initialValue provided)
- CurValue (the element currently being processed in the array)
- CurIndex (the index of the current element in the array)
- Array (array of calls to reduce)
Manual implementation
Define a function myFunction (callback,initialValue);
An error is raised if this or callback is not syntactically correct; This refers to the array that calls Reduce
Wrap the value of the call into a class Object with Object(this). As follows, this pointing to 1212 can also be executed because Object(1212) is converted to Number {1212}
Array.prototype.reduce.call(1212,(pre,cur)=>{return ''+pre+cur},0)
0
Copy the code
Array.prototype.MyReduce = MyReduce;
Function MyReduce(fun, initValue) {if (this === null) {// This does not exist, Throw new TypeError(' array.prototype. reduce '+ 'called on null or undefined'); } if (typeof fun ! == 'function') {throw new TypeError(fun + 'is not a function'); } const value = Object(this); let preValue, curValue, curIndex; if (initValue ! == undefined) { preValue = initValue; curValue = arr[0]; curIndex = 0; } else { preValue = arr[0]; curValue = arr[1]; curIndex = 1 } for (let i = curIndex; i < value.length; i++) { const item = value[i]; preValue = fun(preValue, item, i, arr); } return preValue; } function setReduce(preValue, curValue, index, arr) { return `${preValue} - ${curValue}`; } array.prototype. MyReduce = MyReduce;Copy the code
test
Call the test directly by defining an array
const arr1=[1, 2, 3, 4, 5] let num = arr1.MyReduce(setReduce); console.log(num); / / 15Copy the code
Conclusion:
Reduce () is a merging method of arrays. Like forEach(), map(), filter() and other iterative methods, reduce traverses each item of an array.
Reduce () can simultaneously calculate the result of traversal of the previous array item with the current traversal item, which is impossible for other iterative methods.
Reduce () can be used as a higher-order function for compose of functions. The compose function in Redux can be used to learn how to implement the compose function manually.