feat(utils): cache with ttl

This commit is contained in:
Tomas Martykan
2025-01-07 12:16:45 +01:00
committed by Tomáš Klíma
parent 2f7a039ec8
commit 3c07bce818
3 changed files with 62 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
/**
* Cache class which allows to store Key-Value pairs with a TTL for each key
*/
export class Cache {
store: Map<string, { value: any; ttl: number }>;
constructor() {
this.store = new Map();
}
set(key: string, value: any, ttl: number) {
this.store.set(key, { value, ttl: Date.now() + ttl });
}
get(key: string) {
const entry = this.store.get(key);
if (!entry) return;
if (entry.ttl < Date.now()) {
this.store.delete(key);
return;
}
return entry.value;
}
delete(key: string) {
this.store.delete(key);
}
}

View File

@@ -8,6 +8,7 @@ export * from './arrayPartition';
export * from './arrayShuffle';
export * from './arrayToDictionary';
export * from './bytesToHumanReadable';
export * from './cache';
export * from './capitalizeFirstLetter';
export * from './cloneObject';
export * from './countBytesInString';

View File

@@ -0,0 +1,31 @@
import { Cache } from '../src/cache';
const delay = (ms: number) => jest.advanceTimersByTime(ms);
const TTL = 100;
describe('Cache', () => {
let cache: Cache;
beforeEach(() => {
jest.useFakeTimers();
cache = new Cache();
});
it('set and get', () => {
cache.set('key', 'value', TTL);
expect(cache.get('key')).toEqual('value');
});
it('get with expired TTL', () => {
cache.set('key', 'value', TTL);
delay(TTL + 1);
expect(cache.get('key')).toBeUndefined();
});
it('delete', () => {
cache.set('key', 'value', TTL);
cache.delete('key');
expect(cache.get('key')).toBeUndefined();
});
});