编写函数求组合数,函数式编程入门
模拟lodash中的flowRight
组合函数原理模拟function compose(...args) { return function(value) { return args.reverse().reduce(function(acc, fn) { return fn(acc) }, value) }}const last1 = compose(toUpPer, first, reverse)console.log(last1(array)); //FIVE//使用箭头函数重写const compose = (...args) => (value) => args.reverse().reduce((acc, fn) => fn(acc), value)const last1 = compose(toUpPer, first, reverse)console.log(last1(array)); //FIVE 函数组合要满足的条件 函数的组合要满足结合律(associativity)我们既可以把g和h组合 ,还可以吧把f和g组合,结果都是一样的let f = compose(f, g, h)let associative = compose(compose(f,g,h)) == compose(f,compose(g,h))举例 使用lodash自带的函数组合const last = _.flowRight(_.toUpper, _.first, _.reverse); console.log(last(array));//FIVEconst last = _.flowRight(_.flowRight(_.toUpper, _.first), _.reverse); console.log(last(array));//FIVEconst last = _.flowRight(_.toUpper, _.flowRight(_.first, _.reverse)); console.log(last(array));//FIVE谢谢大家观看 如有不足敬请指教