Skip to content

Commit 3c07bce

Browse files
martykantomasklim
authored andcommitted
feat(utils): cache with ttl
1 parent 2f7a039 commit 3c07bce

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

packages/utils/src/cache.ts

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Cache class which allows to store Key-Value pairs with a TTL for each key
3+
*/
4+
export class Cache {
5+
store: Map<string, { value: any; ttl: number }>;
6+
7+
constructor() {
8+
this.store = new Map();
9+
}
10+
11+
set(key: string, value: any, ttl: number) {
12+
this.store.set(key, { value, ttl: Date.now() + ttl });
13+
}
14+
15+
get(key: string) {
16+
const entry = this.store.get(key);
17+
if (!entry) return;
18+
if (entry.ttl < Date.now()) {
19+
this.store.delete(key);
20+
21+
return;
22+
}
23+
24+
return entry.value;
25+
}
26+
27+
delete(key: string) {
28+
this.store.delete(key);
29+
}
30+
}

packages/utils/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export * from './arrayPartition';
88
export * from './arrayShuffle';
99
export * from './arrayToDictionary';
1010
export * from './bytesToHumanReadable';
11+
export * from './cache';
1112
export * from './capitalizeFirstLetter';
1213
export * from './cloneObject';
1314
export * from './countBytesInString';

packages/utils/tests/cache.test.ts

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { Cache } from '../src/cache';
2+
3+
const delay = (ms: number) => jest.advanceTimersByTime(ms);
4+
5+
const TTL = 100;
6+
7+
describe('Cache', () => {
8+
let cache: Cache;
9+
10+
beforeEach(() => {
11+
jest.useFakeTimers();
12+
cache = new Cache();
13+
});
14+
15+
it('set and get', () => {
16+
cache.set('key', 'value', TTL);
17+
expect(cache.get('key')).toEqual('value');
18+
});
19+
20+
it('get with expired TTL', () => {
21+
cache.set('key', 'value', TTL);
22+
delay(TTL + 1);
23+
expect(cache.get('key')).toBeUndefined();
24+
});
25+
26+
it('delete', () => {
27+
cache.set('key', 'value', TTL);
28+
cache.delete('key');
29+
expect(cache.get('key')).toBeUndefined();
30+
});
31+
});

0 commit comments

Comments
 (0)