All files / compose compose.ts

100% Statements 4/4
100% Branches 0/0
100% Functions 3/3
100% Lines 2/2

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20                                1x 3x    
/**
 * @description 函数组合。将两个或两个以上的函数组合生成一个新函数,新函数会按照栈顺序执行传入函数
 * @function compose
 * @param {Array.Function} funcs - 函数组成的数组
 * @returns {Function} 返回一个执行函数,可传入需要处理的参数
 * @author liukun <919590347@qq.com>
 * @example
 * import { compose } from '@wont/utils'
 * const trim = (str) => str.trim()
 * const toLowerCase = (str) => str.toLowerCase()
 * const split = (str, sep = ',') => str.split(sep)
 * const getResult = compose([trim, toLowerCase, split])
 * getResult('a,b,c ') // returns [a, b, c]
 */
 
type Fn = (...rest: any[]) => any
export function compose(funcs: Fn[]): Fn {
  return (param) => funcs.reduce((arg, fn) => fn(arg), param)
}