理解概念
函数式编程是一种编程范式,例如面向对象编程
函数式编程的主要思想是:把事物之间的联系抽象到程序中,对运算过程进行抽象
指的是数学中函数的映射关系 相同的输入始终要有相同的输出
//非函数式
let a = 1
let b = 2
let c = a+b
alert(c)
// 函数式
let sum = (a ,b) => a + b
alert(sum(1, 3))
高阶函数
- 把函数作为参数,传递给另一个函数
- 可以把函数作为另一个函数的返回结果
高阶函数 可以帮助我们屏蔽实现的细节,只需要关注我们的目标
// 过滤器
function filter(arr, func) {
let copyArray = []
for (let i = 0; i < arr.length; i++) {
const element = arr[i];
if (func(element)) {
copyArray.push(element)
}
}
return copyArray
}
const arr = [2, 5, 1, 6, 10, 7]
// 函数作为参数
let res = filter(arr, function (item) {
return item % 2 === 0 // 返回偶数
})
console.log(res) // 2,6,10
// 只执行一次
function once(func) {
let done = false
return function () {
if (!done) {
done = true
return func.apply(this, arguments)
}
}
}
// 函数作为另一个函数的返回结果
const payMoney = once(function (num) {
console.log(`支付成功${num}元`)
})
payMoney(1) // 支付成功1元
payMoney(2)
payMoney(3)
payMoney(4)
payMoney(5)
闭包
上面写的once()函数其实就是一个闭包。
闭包的本质:函数执行的时候会放到一个执行栈上,当函数执行完毕会从执行栈上移除,但是堆上的作用域成员因为被外部引用不能释放,内部函数依然可以访问外部函数成员(延长局部变量的生命周期)
柯里化
当一个函数有多个参数的时候,先传递一部分调用它(这部分参数以后永远不变)
然后返回一个新的函数 接收剩余的参数,返回结果
const _ = require('lodash')
// 正则匹配
const match = _.curry((reg, str) => str.match(reg)
)
// 查找空格
const havaSpace = match(/\s+/g)
// 查找数字
const havaNumber = match(/\d+/g)
console.log(havaSpace('hello feir'))
console.log(havaNumber('hello feir'))
// 过滤数组
const filter = _.curry((func, array) => array.filter(func)
)
console.log(filter(havaSpace, ['feir hello', 'feir_hello']))
// 柯里化 只传递一个参数
const findSpace = filter(havaSpace) // 查找出有空格的元素
console.log(findSpace(['feir hello', 'feir_hello']))
//模拟一个curry
function curry(func) {
return function curridfn(...args) {
// args 实参 func.length 形参
if (args.length < func.length) {
return function () { //形成了一个闭包
return curridfn(...args.concat(Array.from(arguments)))
}
} else {
return func(...args)
}
}
}
const getSum = (a, b, c) => a + b + c
const currid = curry(getSum)
console.log(currid(1)(4, 5))
组合函数模拟
const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()
const compose = (...args) => value => args.reverse().reduce((acc, fn) => fn(acc), value)
const f = compose(toUpper, first, reverse)
console.log(f(['tom', 'cat', 'jesse']))
functor
// 函子
class Container {
static of(value) {
return new Container(value)
}
constructor(value) {
this._value = value // 私有属性
}
map(fn) {
return new Container(fn(this._value))
}
}
let a = Container.of(5)
.map(x => x + 1)
.map(x => x * x)
console.log(a)
网友评论