forked from lodash/lodash
-
Notifications
You must be signed in to change notification settings - Fork 1
/
flow.js
41 lines (40 loc) · 1005 Bytes
/
flow.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Composes a function that returns the result of invoking the given functions
* with the `this` binding of the created function, where each successive
* invocation is supplied the return value of the previous.
*
* @since 3.0.0
* @category Util
* @param {Function[]} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see flowRight
* @example
*
* import add from 'lodash/add'
*
* function square(n) {
* return n * n
* }
*
* const addSquare = flow(add, square)
* addSquare(1, 2)
* // => 9
*/
function flow(...funcs) {
const length = funcs.length
let index = length
while (index--) {
if (typeof funcs[index] !== 'function') {
throw new TypeError('Expected a 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
}
}
export default flow