UNPKG

765 BJavaScriptView Raw
1'use strict'
2
3let cache = {}
4let hits = []
5
6function 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// Ensure that the last X keys are always available
15memoize.keepKeys = 20
16
17// Truncate every now and then
18memoize.truncateInterval = 3 * 60 * 1000
19
20// truncate the cache to the last N keys used
21memoize.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// truncate every few minutes
34memoize.timer = setInterval(memoize.prune, memoize.truncateInterval)
35
36module.exports = memoize