Last active
April 10, 2025 13:15
-
-
Save nazaslater/9aa2d91ff13db53466768fd89ba4733e to your computer and use it in GitHub Desktop.
Função de memoização em TypeScript com suporte a TTL e limite de tamanho de cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Memoiza o resultado de uma função com suporte a múltiplos parâmetros, | |
* controle de expiração por tempo (TTL) e limite de tamanho do cache. | |
* | |
* @param fn - A função original a ser memoizada. | |
* @param options - Configurações opcionais: maxSize (número máx. de itens no cache), ttl (tempo em ms). | |
* @returns Uma nova função que cacheia os resultados com base nos argumentos. | |
*/ | |
export function memoize<T extends (...args: any[]) => any>( | |
fn: T, | |
options: { maxSize?: number; ttl?: number } = {} | |
): T { | |
const cache = new Map<string, { value: ReturnType<T>; timestamp: number }>(); | |
const { maxSize = Infinity, ttl = Infinity } = options; | |
return function (...args: Parameters<T>): ReturnType<T> { | |
const key = JSON.stringify(args); | |
const cached = cache.get(key); | |
if (cached) { | |
if (ttl === Infinity || Date.now() - cached.timestamp < ttl) { | |
return cached.value; | |
} | |
cache.delete(key); // Cache expirado | |
} | |
const result = fn(...args); | |
if (maxSize !== Infinity && cache.size >= maxSize) { | |
const oldestKey = cache.keys().next().value; | |
cache.delete(oldestKey); | |
} | |
cache.set(key, { value: result, timestamp: Date.now() }); | |
return result; | |
} as T; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment