概念
纯函数和柯里化很容易写出洋葱代码
_.toUpper(_.first(_.reverse(array))); //这样就是洋葱代码 一层套一层
函数组合可以把细粒度的函数重新组合成一个新函数
函数组合(compose):如果一个函数要经过多个函数处理才能得到最终值,
这个时候可以把中间过程的函数合并成一个函数
函数就像是数据的管道,函数组合就是把这些管道连接起来,
网数据穿过多个管道形成最终的结果
函数组合默认是从右往左执行
function compose(f, g) {
return function(value) {
return f(g(value))
}
};
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function reverse(array) {
//数组的逆转
return array.reverse(array)
};
function first(array) {
//拿到数组的第一位
return array[0]
}
//先执行reverse函数 后执行first函数
const last = compose(first, reverse)
console.log(last(arr)); //9
lodash中的组合函数
1、flow()函数 从左往右执行
2、flowRight()函数 从右往左执行 这个函数用的多一些
这两个都可以组合多个函数
举例:
//定义数组
let array = ['first', 'second', 'third', 'four', 'five'];
//数组逆转
const reverse = arr => arr.reverse();
//数组的第一个
const first = arr => arr[0]
//转换大写
const toUpPer = element => element.toUpperCase()
//封装方法
const last = _.flowRight(toUpPer, first, reverse)
//得到结果
console.log(last(array)); //FIVE
组合函数实现原理
模拟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));//FIVE
const last = _.flowRight(_.flowRight(_.toUpper, _.first), _.reverse);
console.log(last(array));//FIVE
const last = _.flowRight(_.toUpper, _.flowRight(_.first, _.reverse));
console.log(last(array));//FIVE
谢谢大家观看 如有不足敬请指教