1 | 'use strict'
|
2 |
|
3 | let cache = {}
|
4 | let hits = []
|
5 |
|
6 | function memoize (keyObject, fn) {
|
7 | const key = JSON.stringify(keyObject)
|
8 | if (cache[key]) return cache[key]
|
9 | cache[key] = fn()
|
10 | hits.push(key)
|
11 | return cache[key]
|
12 | }
|
13 |
|
14 |
|
15 | memoize.keepKeys = 20
|
16 |
|
17 |
|
18 | memoize.truncateInterval = 3 * 60 * 1000
|
19 |
|
20 |
|
21 | memoize.prune = function prune () {
|
22 | const preserved = hits.slice(hits.length - memoize.keepKeys)
|
23 | const newCache = {}
|
24 |
|
25 | preserved.forEach((key) => {
|
26 | newCache[key] = cache[key]
|
27 | })
|
28 |
|
29 | hits = preserved
|
30 | cache = newCache
|
31 | }
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | module.exports = memoize
|