函数式编程-函数组合篇

在这里插入图片描述

概念
纯函数和柯里化很容易写出洋葱代码
_.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

谢谢大家观看 如有不足敬请指教

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值