/** ***************************************** * Created by edonet@163.com * Created on 2021-04-02 21:24:10 ***************************************** */ 'use strict'; /** ***************************************** * 处理函数 ***************************************** */ type Handler = (state: T, next: () => void | P) => void | P; /** ***************************************** * 链函数 ***************************************** */ type Chain = (state: T, callback?: (state: T) => void | P) => void | P; /** ***************************************** * 函数链 ***************************************** */ export function chain(...args: Handler[]): Chain { const length = args.length; // 校验参数 args.forEach(handler => { if (typeof handler !== 'function') { throw new Error('expect handler to be a function!'); } }); // 执行函数 function invoke(index: number, state: T, callback?: (state: T) => void | P): void | P { if (index < length) { return args[index](state, () => invoke(index + 1, state, callback)); } // 执行回调 if (typeof callback === 'function') { return callback(state); } } // 返回函数 return function chained(state, callback) { return invoke(0, state, callback); }; }