Skip to content

Commit

Permalink
add noDisposeOnSet option
Browse files Browse the repository at this point in the history
Close #70
  • Loading branch information
faascape authored and isaacs committed Jun 6, 2017
1 parent c65bd6f commit 4ef200a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
4 changes: 4 additions & 0 deletions README.md
Expand Up @@ -66,6 +66,10 @@ away.
`stale:true`, it'll return the stale value before deleting it. If
you don't set this, then it'll return `undefined` when you try to
get a stale entry, as if it had already been deleted.
* `noDisposeOnSet` By default, if you set a `dispose()` method, then
it'll be called whenever a `set()` operation overwrites an existing
key. If you set this option, `dispose()` will only be called when a
key falls out of the cache, not when it is overwritten.

## API

Expand Down
7 changes: 5 additions & 2 deletions lib/lru-cache.js
Expand Up @@ -12,7 +12,6 @@ var Yallist = require('yallist')
var symbols = {}
var hasSymbol = typeof Symbol === 'function'
var makeSymbol
/* istanbul ignore if */
if (hasSymbol) {
makeSymbol = function (key) {
return Symbol.for(key)
Expand Down Expand Up @@ -79,6 +78,7 @@ function LRUCache (options) {
priv(this, 'allowStale', options.stale || false)
priv(this, 'maxAge', options.maxAge || 0)
priv(this, 'dispose', options.dispose)
priv(this, 'noDisposeOnSet', options.noDisposeOnSet || false)
this.reset()
}

Expand Down Expand Up @@ -314,8 +314,11 @@ LRUCache.prototype.set = function (key, value, maxAge) {
var item = node.value

// dispose of the old one before overwriting
// split out into 2 ifs for better coverage tracking
if (priv(this, 'dispose')) {
priv(this, 'dispose').call(this, key, item.value)
if (!priv(this, 'noDisposeOnSet')) {
priv(this, 'dispose').call(this, key, item.value)
}
}

item.now = now
Expand Down
16 changes: 16 additions & 0 deletions test/basic.js
Expand Up @@ -300,6 +300,22 @@ test('disposal function', function (t) {
t.end()
})

test('no dispose on set', function (t) {
var disposed = false
var cache = new LRU({
max: 1,
noDisposeOnSet: true,
dispose: function (k, n) {
disposed = n
}
})

cache.set(1, 1)
cache.set(1, 10)
t.equal(disposed, false)
t.end()
})

test('disposal function on too big of item', function (t) {
var disposed = false
var cache = new LRU({
Expand Down

0 comments on commit 4ef200a

Please sign in to comment.