import { type Trie } from '@kamilmielnik/trie'; import { type Locale } from '@scrabble-solver/types'; import { CACHE_STALE_THRESHOLD } from '../constants'; import type { Cache } from '../types'; export class MemoryCache implements Cache { private readonly cache: Partial> = {}; private readonly cacheTimestamps: Partial> = {}; public get(locale: Locale): Promise { return Promise.resolve(this.cache[locale]); } public getLastModifiedTimestamp(locale: Locale): number | undefined { return this.cacheTimestamps[locale]; } public has(locale: Locale): boolean { return typeof this.cache[locale] !== 'undefined'; } public isStale(locale: Locale): boolean | undefined { const timestamp = this.getLastModifiedTimestamp(locale); if (!this.has(locale) || typeof timestamp === 'undefined') { return undefined; } const timeSinceModification = Math.abs(timestamp - Date.now()); return timeSinceModification > CACHE_STALE_THRESHOLD; } public set(locale: Locale, trie: Trie): Promise { this.cacheTimestamps[locale] = Date.now(); this.cache[locale] = trie; return Promise.resolve(); } }