What does the lodash flow function do?

前端 未结 2 1047
醉话见心
醉话见心 2021-01-17 10:34

I am reading some code that uses _.flow() from lodash and the explanation in the docs just isn\'t making sense to me.

The doc says

Creates a

相关标签:
2条回答
  • 2021-01-17 11:10

    Rewording the definition from the docs in simpler terms: It calls, in order, the methods in the array. It uses the result from each function as the parameters for the next function. In the case of the example given, the steps are as follows:

    1. Invokes _.add(1, 2), which returns 3.
    2. Passes that return value as the parameter to the next function in the array, which becomes square(3). This returns 9.
    0 讨论(0)
  • 2021-01-17 11:14

    Here is the relevant part of the source code for this function:

    return function(...args) {
        let index = 0
        let result = length ? funcs[index].apply(this, args) : args[0]
        while (++index < length) {
            result = funcs[index].call(this, result)
        }
        return result
    }
    

    So it first applies the first function to the input arguments; then calls the rest of the functions with each taking up the result of the previous stage.

    I can see the following benefits from doing it this way: - All the applied functions will use the this argument of the caller in case that is desired. - On definition, it just returns a function. This allows for lazy evaluation. The flow function can be passed around. The actual calculation will take place only when it is applied to the arguments.

    0 讨论(0)
提交回复
热议问题