Skip to content

Commit

Permalink
Fix incorrect maxAge being set when used on .set() (sindresorhus#36)
Browse files Browse the repository at this point in the history
  • Loading branch information
Javier Blanco authored Nov 21, 2021
1 parent 6ee4b6e commit 6a9c875
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
10 changes: 7 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,14 +110,18 @@ export default class QuickLRU {
}
}

set(key, value, {maxAge = this.maxAge === Number.POSITIVE_INFINITY ? undefined : Date.now() + this.maxAge} = {}) {
set(key, value, {maxAge = this.maxAge} = {}) {
const expiry =
typeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY ?
Date.now() + maxAge :
undefined;
if (this.cache.has(key)) {
this.cache.set(key, {
value,
expiry: maxAge
expiry
});
} else {
this._set(key, {value, expiry: maxAge});
this._set(key, {value, expiry});
}
}

Expand Down
8 changes: 4 additions & 4 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,14 +219,14 @@ test('`onEviction` option method is called after `maxSize` is exceeded', t => {

test('set(expiry) - an individual item could have custom expiration', async t => {
const lru = new QuickLRU({maxSize: 10});
lru.set('1', 'test', {maxAge: Date.now() + 100});
lru.set('1', 'test', {maxAge: 100});
await delay(200);
t.false(lru.has('1'));
});

test('set(expiry) - items without expiration will never expired', async t => {
const lru = new QuickLRU({maxSize: 10});
lru.set('1', 'test', {maxAge: Date.now() + 100});
lru.set('1', 'test', {maxAge: 100});
lru.set('2', 'boo');
await delay(200);
t.false(lru.has('1'));
Expand All @@ -246,7 +246,7 @@ test('set(expiry) - not a number expires should not be take in account', async t

test('set(expiry) - local expires prevails over the global maxAge', async t => {
const lru = new QuickLRU({maxSize: 10, maxAge: 1000});
lru.set('1', 'test', {maxAge: Date.now() + 100});
lru.set('1', 'test', {maxAge: 100});
lru.set('2', 'boo');
await delay(300);
t.false(lru.has('1'));
Expand Down Expand Up @@ -291,7 +291,7 @@ test('max age - setting the item again should refresh the expiration time', asyn
test('max age - setting an item with a local expiration date', async t => {
const lru = new QuickLRU({maxSize: 2, maxAge: 100});
lru.set('1', 'test');
lru.set('2', 'test2', {maxAge: Date.now() + 500});
lru.set('2', 'test2', {maxAge: 500});
await delay(200);
t.true(lru.has('2'));
await delay(300);
Expand Down

0 comments on commit 6a9c875

Please sign in to comment.