定义:将纯函数作为第一公民,实现功能的开发
纯函数:无状态 && 无副作用的函数
无状态:函数不依赖或修改外部状态
无副作用:函数运行不对外部产生影响
let x = 9
let y = 10
function add() {
return x + y // 依赖了外部变量,这就是有状态的
}
add()
function reset() {
x = 0 // 改变了外部变量,这就是副作用
y = 0 // 改变了外部变量,这就是副作用
}
reset()
所以函数式编程就是尽可能多的用纯函数去编程
let x = 9
let y = 10
function add(_x, _y) {
return _x + _y // 不依赖外部变量,只依赖参数
}
add(x, y)
function reset() {
return 0
}
x = reset()
y = reset()
高阶函数:【参数为函数,返回为函数】的函数
const compose = (f, g) => x => f(g(x))
const sum1 = x => x + 1
const sum2 = x => x + 2
const sum = compose(sum1, sum2)
sum(5) // 8
应用场景:
防抖:t 时间后执行一次(每次操作重置 t)
const debounce = (cb, time) => {
let timer = null;
return function() {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments)
}, delay)
}
}
节流:t 时间内只执行一次
const throttle = (cb, time) => {
let timer = null;
return function() {
if(!timer) {
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, time)
}
}
}