Skip to content

Commit

Permalink
feat: support redis-like ttl as third argument (closes sindresorhus#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
titanism committed Feb 27, 2023
1 parent 7713928 commit e4f2617
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 2 deletions.
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export default class QuickLRU<KeyType, ValueType> extends Map implements Iterabl
@returns The list instance.
*/
set(key: KeyType, value: ValueType, options?: {maxAge?: number}): this;
set(key: KeyType, value: ValueType, options?: number | {maxAge?: number}): this;

/**
Get an item.
Expand Down
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,14 @@ export default class QuickLRU extends Map {
}
}

set(key, value, {maxAge = this.maxAge} = {}) {
set(key, value, options = {}) {
let {maxAge} = this;
if (typeof options === 'number') {
maxAge = options;
} else if (typeof options === 'object' && typeof options.maxAge === 'number') {
maxAge = options.maxAge;
}

const expiry =
typeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY ?
Date.now() + maxAge :
Expand Down
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ Set an item. Returns the instance.

Individual expiration of an item can be specified with the `maxAge` option. If not specified, the global `maxAge` value will be used in case it is specified on the constructor, otherwise the item will never expire.

Options can either be a Number or an Object (e.g. a TTL to expire in 1 second: `lru.set(key, value, 1000)` or `lru.set(key, value, { maxAge: 1000 })`).

#### .get(key)

Get an item.
Expand Down
10 changes: 10 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,16 @@ test('set(expiry) - local expires prevails over the global maxAge', async t => {
t.true(lru.has('2'));
});

test('set(expiry) - local expires prevails over the global maxAge (third argument Number)', async t => {
const lru = new QuickLRU({maxSize: 10, maxAge: 1000});
lru.set('1', 'test', 100);
lru.set('2', 'boo');
await delay(300);
t.false(lru.has('1'));
await delay(200);
t.true(lru.has('2'));
});

test('set(expiry) - set the same item should update the expiration time', async t => {
const lru = new QuickLRU({maxSize: 10, maxAge: 150});
lru.set('1', 'test');
Expand Down

0 comments on commit e4f2617

Please sign in to comment.