1、只调用一次函数
function once(fn) {
let done = false
return function () {
if (!done) {
done = true
return fn.apply(this, arguments)
}
}
}
let pay = once(function (money) {
console.log('money', money)
})
pay(5)
pay(4)
2、函数缓存
function getArea(r) {
console.log('执行area')
return Math.PI * r * r
}
function memoize(f) {
let catche = {}
return function () {
let key = JSON.stringify(arguments)
catche[key] = catche[key] || f.apply(f, arguments)
return catche[key]
}
}
let getAreaWithMemoize = memoize(getArea)
console.log(getAreaWithMemoize(4))
console.log(getAreaWithMemoize(4))
console.log(getAreaWithMemoize(4))