进阶学习3:函数式编程FP——函数的组合、组合函数模拟、Lodash fp模块、PointFree

目录

五、函数的组合

1.函数组合的概念

管道:

函数组合 (compose)

2.Lodash中的组合函数

3.组合函数原理模拟

4.函数组合——结合律

5.函数组合——调试

6.Lodash——FP模块 

Lodash FP模块介绍

 Lodash和Lodash/fp模块中map方法的区别

7.Point Free


五、函数的组合

1.函数组合的概念

纯函数和柯里化很容易写出洋葱代码 h(g(f(x)))

管道:

函数组合 (compose)

如果一个函数要经过多个函数处理才能得到最终值,这个时候可以把中间过程的函数合并成一个函数

  • 函数就像是数据的管道,函数组合就是把这些管道连接起来,让数据穿过多个管道形成最终结果
  • 函数组合默认是从右到左执行
//DEMO16
//函数组合样式
//其实没有变简单,只是被封装起来了
function compose (f, g){
    return function (value) {
        return f(g(value))
    }
}
//目的:获取数组的最后一个元素
//方法:先反转数组,再获取第一个元素

function reverse (array) {
    return array.reverse()
}
function first (array) {
    return array[0]
}
//因为是从右往左走,所以reverse放在后面
const last = compose(first, reverse)
console.log(last([1,2,3,4]))

结果:

2.Lodash中的组合函数

Lodash 中组合函数 flow() 或者 flowRight(),他们都可以组合多个函数

flow():是从左到右运行

flowRight():是从右到左运行,使用的更多一些

//DEMO17
//lodash函数组合 _.flowRight()
const _ = require('lodash')
//获取最后一个元素的大写
//先反转再取第一个在转换为大写
const reverse = array => array.reverse()
const first = array => array[0]
const toUpper = str => str.toUpperCase()

const last = _.flowRight(toUpper, first, reverse)
console.log(last(["one", "two", "three"]))

结果:

3.组合函数原理模拟

//DEMO17
//lodash_.flowRight()函数模拟
//参数个数不固定
const _ = require('lodash')

const reverse = array => array.reverse()
const first = array => array[0]
const toUpper = str => str.toUpperCase()

const last = compose(toUpper, first, reverse)
console.log(last(["one", "two", "three"]))

function compose (...args){
    return function (value){
        //reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
        //reduce() 可以作为一个高阶函数,用于函数的 compose。
        //acc 累积的结果 
        return args.reverse().reduce(function (acc, fn){
            return fn(acc)
        },value)//设置初始值为value
    }
}

//用箭头函数重写compose
const compose2 = (...args) => value => args.reverse().reduce((acc, fn)=> fn(acc),value)
const last2 = compose2(toUpper, first, reverse)
console.log(last2(["one", "two", "three"]))

结果:

4.函数组合——结合律

函数的组合要满足结合律 (associativity): 我们既可以把 g 和 h 组合,还可以把 f 和 g 组合,结果都是一样的

// 结合律(associativity)
let f = compose(f, g, h)
let associative = compose(compose(f, g), h) == compose(f, compose(g, h))
// true

实例:

//DEMO18
//函数组合结合律
const _ = require('lodash')

const last = _.flowRight(_.toUpper, _.first, _.reverse)
console.log(last(["one", "two", "three"]))

const last2 = _.flowRight( _.flowRight(_.toUpper, _.first), _.reverse)
const last3 = _.flowRight(_.toUpper, _.flowRight(_.first, _.reverse))

console.log(last2(["one", "two", "three"]))
console.log(last3(["one", "two", "three"]))

结果:

5.函数组合——调试

主要是用了trace在中间输出结果,需要柯里化处理

//DEMO18
//函数组合 调试
//NEVER SAY DIE --> never-say-die

const _ = require('lodash')

//_.split() 有多个参数,所以得自己改
const split = _.curry((sep, str) => _.split(str, sep))

// _.toLower()

const join = _.curry((sep, array) => _.join(array, sep))
/*
const log = v => {
    console.log(v)
    return v
}
*/
const trace = _.curry((tag, v) => {
    console.log(tag, v)
    return v
})

const map = _.curry((fn, array) => _.map(array, fn))
const f = _.flowRight(join("-"),_.toLower,split(" "))

//const f_test = _.flowRight(join("-"),_.toLower,log,split(" "))
const f_test2 = _.flowRight(join("-"),trace("after map"),map(_.toLower),trace("before map"),split(" "))


console.log(f('NEVER SAY DIE'))
console.log(f_test2('NEVER SAY DIE'))

6.Lodash——FP模块 

Lodash FP模块介绍

lodash 的 fp 模块提供了实用的对函数式编程友好的方法,提供了不可变 auto-curried iteratee-first data-last 的方法

// lodash 模块
const _ = require('lodash')
_.map(['a', 'b', 'c'], _.toUpper)
// => ['A', 'B', 'C']
_.map(['a', 'b', 'c'])
// => ['a', 'b', 'c']
_.split('Hello World', ' ')
// lodash/fp 模块
const fp = require('lodash/fp')
fp.map(fp.toUpper, ['a', 'b', 'c'])
fp.map(fp.toUpper)(['a', 'b', 'c'])
fp.split(' ', 'Hello World')
fp.split(' ')('Hello World')

lodash fp模块 都是已经被柯里化的函数,flowRight可以直接用 

//DEMO19
//lodash fp模块 都是已经被柯里化的函数,flowRight可以直接用
//NEVER SAY DIE --> never-say-die

const fp = require('lodash/fp')
const f = fp.flowRight(fp.join('-'), fp.map(fp.toLower),fp.split(' '))
console.log(f('NEVER SAY DIE'))

 Lodash和Lodash/fp模块中map方法的区别

//DEMO20
//Lodash和Lodash/fp模块中map方法的区别
const fp = require('lodash/fp')
const _ = require('lodash')
// parseInt() 函数可解析一个字符串,并返回一个整数。
// parseInt("10");			//返回 10
// parseInt("19",10);		//返回 19 (10+9)
// parseInt("11",2);		//返回 3 (2+1)
// parseInt("17",8);		//返回 15 (8+7)
// parseInt("1f",16);		//返回 31 (16+15)
// parseInt("010");		//未定:返回 10 或 8
console.log(_.map(['23','8','18'], parseInt))
// parseInt('23', 0, array)
// parseInt('8', 1, array)
// parseInt('18', 2, array)
console.log(fp.map(parseInt, ['23','8','18']))

结果

解释:如下图文档所示,_.map其实传递3个参数,所以实际上运行的是parseInt('23', 0, array),parseInt('8', 1, array),parseInt('18', 2, array)

7.Point Free

Point Free:我们可以把数据处理的过程定义成与数据无关的合成运算,不需要用到代表数据的那个参 数,只要把简单的运算步骤合成到一起,在使用这种模式之前我们需要定义一些辅助的基本运算函数。

  • 不需要指明处理的数据
  • 只需要合成运算过程
  • 需要定义一些辅助的基本运算函数
const f = fp.flowRight(fp.join('-'), fp.map(_.toLower), fp.split(' '))

样例1: 

//DEMO21
//Point Free
//Hello     World => hello_world
//思路:先转换为小写,把空格换成下划线
const fp = require('lodash/fp')
const f = fp.flowRight(fp.replace(/\s+/,"_"),fp.toLower)
console.log(f('Hello     World'))

结果:

样例2:

//DEMO22
//Point Free
//把一个字符串中的首字母提取并转换为大写,使用. 作为分隔符
//world wild web => W. W. W
const fp = require('lodash/fp')
const firstLetterUpper = fp.flowRight(fp.join('. '),fp.map(fp.first),fp.map(fp.toUpper),fp.split(" "))
console.log(firstLetterUpper('world wild web'))
//这里做了两次map,优化一下只做一次循环
const firstLetterUpper2 = fp.flowRight(fp.join('. '),fp.map(fp.flowRight(fp.first,fp.toUpper)),fp.split(" "))
console.log(firstLetterUpper2('world wild web'))

结果: 

除了上述直接引用外的参考资料:

1.拉勾网 《大前端训练营》课程

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值