Skip to content

Commit

Permalink
Update memoize() to prune properly
Browse files Browse the repository at this point in the history
  • Loading branch information
rstacruz committed Oct 19, 2015
1 parent b21eaf2 commit b5b10c9
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/memoize.js
@@ -1,11 +1,13 @@
'use strict'

let cache = {}
let hits = []

function memoize (keyObject, fn) {
const key = JSON.stringify(keyObject)
if (cache[key]) return cache[key]
cache[key] = fn()
hits.push(key)
return cache[key]
}

Expand All @@ -17,14 +19,14 @@ memoize.truncateInterval = 3 * 60 * 1000

// truncate the cache to the last N keys used
memoize.prune = function prune () {
const keys = Object.keys(cache)
const preserved = keys.slice(keys.length - memoize.keepKeys)
const preserved = hits.slice(hits.length - memoize.keepKeys)
const newCache = {}

preserved.forEach((key) => {
newCache[key] = cache[key]
})

hits = preserved
cache = newCache
}

Expand Down

0 comments on commit b5b10c9

Please sign in to comment.