diff --git a/src/cache.ts b/src/cache.ts index d570eb4..cc1d767 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -1,4 +1,5 @@ import { CacheInterface } from './types/cache_interface.js' +import { KeyValuePairInterface } from './types/key_value_pair_interface.js' /** * Cache is a class that implements the CacheInterface interface. @@ -7,7 +8,7 @@ import { CacheInterface } from './types/cache_interface.js' * @implements {CacheInterface} */ export class Cache implements CacheInterface { - protected cache: Map + protected cache: Map> constructor() { this.cache = new Map() @@ -18,17 +19,16 @@ export class Cache implements CacheInterface { if (!entry) return undefined const now = Date.now() - if (now >= entry.expiry) { - console.log('Cache entry expired') + if (entry.expiry && now >= entry.expiry) { this.cache.delete(key) return undefined } return entry.value } - set(key: string, value: object, ttl?: number): void { - const expiry = ttl ? Date.now() + ttl : Number.POSITIVE_INFINITY - this.cache.set(key, { value, expiry }) + set(pair: KeyValuePairInterface): void { + const expiry = pair.expiry ? Date.now() + pair.expiry : Number.POSITIVE_INFINITY + this.cache.set(pair.key, { value: pair.value, expiry }) } has(key: string): boolean { @@ -39,7 +39,7 @@ export class Cache implements CacheInterface { const now = Date.now() return Array.from(this.cache.entries()) .filter(([key, { expiry }]) => { - if (now >= expiry) { + if (expiry && now >= expiry) { this.cache.delete(key) return false } diff --git a/src/types/cache_interface.ts b/src/types/cache_interface.ts index da9e23b..b7d4241 100644 --- a/src/types/cache_interface.ts +++ b/src/types/cache_interface.ts @@ -1,3 +1,5 @@ +import { KeyValuePairInterface } from './key_value_pair_interface.js' + /** * CacheInterface is an interface that defines the structure of a cache object. * It includes methods for getting, setting, deleting, and clearing cache entries, @@ -15,11 +17,9 @@ export interface CacheInterface { /** * Sets the value of a cache entry with the specified key. - * @param key - The key of the cache entry. - * @param value - The value to set for the cache entry. - * @param ttl - The time-to-live (in seconds) for the cache entry. Optional. + * @param pair - The key-value pair to be set. */ - set(key: string, value: object, ttl?: number): void + set(pair: KeyValuePairInterface): void /** * Deletes a cache entry with the specified key. diff --git a/src/types/key_value_pair_interface.ts b/src/types/key_value_pair_interface.ts new file mode 100644 index 0000000..f027cf0 --- /dev/null +++ b/src/types/key_value_pair_interface.ts @@ -0,0 +1,5 @@ +export interface KeyValuePairInterface { + key: string + value: object + expiry?: number +}