2019-04-06 09:49:02 +08:00
|
|
|
```js
|
|
|
|
function cacher(fn) {
|
|
|
|
const cache = {}
|
|
|
|
return function () {
|
|
|
|
const key = [...arguments].join('-')
|
|
|
|
if (cache.hasOwnProperty(key)) return cache[key]
|
|
|
|
const result = fn.apply(null, arguments)
|
|
|
|
cache[key] = result
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-09 09:26:47 +08:00
|
|
|
const add = cacher((a, b) => a + b)
|
2019-04-06 09:49:02 +08:00
|
|
|
|
|
|
|
|
|
|
|
add(1, 3) //第一次计算
|
|
|
|
add(1, 3) //第二次直接从cache里取
|
|
|
|
```
|