The usage of Reduce
Reduce is an array operation, typically used to “accumulate” all the members of an array into a single value:
Reduce executes sum on each member of the array ARR. The argument a to sum is the cumulative variable, and the argument B is the current array member. Each time it executes, b is added to A, and a is printed.
The cumulative variable must have an initial value, as in the above examplereduce
The second argument to the function0
. If omitted, the initial value defaults to the first member of the array.
The corresponding API is as follows:
Second, the nature of Reduce
- traverse
- deformation
- The cumulative
Map is a special case of Reduce: the initial value of a cumulative variable can also be an array
Reduce is useful because it contains three operations. But there is a problem: the code is not reusable. In Reduce, deformation and accumulation are coupled and not easily separated.
Compose function in reduce and Redux
So after learning reduce, try to write a function that can combine multiple functions into one function, namely unary chain function. Such as:
Write a function using reduce so that both functions perform the same result
The code implementation is as follows:
function chained(funcs) { return function(params){ return funcs.reduce(function(params, fn){ return fn(params) }, params); }}Copy the code
The verification is as follows:
Consider the compose function implementation in redux:
Note here: Reduce is processed from left to right (from the first member to the last member), reduceRight is processed from right to left (from the last member to the first member), everything else is exactly the same.
function chained(... funcs) { if (funcs.length === 0) { return arg => arg } if (funcs.length === 1) { return funcs[0] } return funcs.reduce((a, b) => (... args) => b(a(... args))) }Copy the code
Loadsh compose function implementation source code is attached.
var flow = function(funcs) { var length = funcs.length var index = length while (index--) { if (typeof funcs[index] ! == 'function') { throw new TypeError('Expected a function'); } } return function(... args) { var index = 0 var result = length ? funcs[index].apply(this, args) : args[0] while (++index < length) { result = funcs[index].call(this, result) } return result } } var flowRight = function(funcs) { return flow(funcs.reverse()) }Copy the code