background
The compose function in Redux is now used to augment the store. Here is an example of how redux can be used:
For example, the compose method is now in the compose compose compose method, so I’m interested to know how it works
The role of the composer
Fn1 (fn2(fn3(fn3(fn3(... args))))-->compose(fn1,fn2,fn3,fn4)(... Args) such a simple readable way to call a functionCopy the code
The source code
Here is the source compose method in the Github Redux project compose.js
export default function compose(... Funcs) {if (funcs.length === 0) {return arg => arg} If (funcs.length === 1) {return funcs[0]} return funcs.reduce((a, b) => (... args) => a(b(... args))) }Copy the code
Although the reduce method is often used, the code above is only 8 lines of code, but it is still a little confusing. If you look closely at the core code, it is actually only one line
return funcs.reduce((a, b) => (... args) => a(b(... args)))Copy the code
Analysis to understand
Looking at this line of concise to the extreme code, a little headache, think about his execution process is what kind of, confused, or blame their logical thinking is a little poor, have to chicken can only simulate, step by step analysis
let str = 1 function add1(str) {return str + 1} function add2(str) { return str + 2} function add3(str) { return str + For compose, let a = add1(add2(add3(STR))) // for compose, let a = add1(add2(STR)), 1 + 3 + 2 + 1 = 7 Let composeFn = compose(add1,add2,add3)(STR)// Should also theoretically get 7Copy the code
- Componse execution returns a function
- Parameter componse for the function, the function returned when the implementation of the implementation of the parameter function from right to left and each parameter function to execute the result of the next parameter function to execute the input parameter, return function to execute the input parameter as the first time to execute the parameter function
Look at the execution
Number of cycles | The value of a | The value of b | The value returned |
---|---|---|---|
First cycle | add1 | add2 | (… args) => add1(add2(… args))) |
Second cycle | (… args) => add1(add2(… args))) | add3 | (… args) => add1(add2(add3(… args)))) |
conclusion
So when you do that and you add arguments to it you end up with add1(add2(add3(1))))) and when you do that, you’re essentially writing a function that combines multiple functions into one function, which is a unary chain function