UNPKG

@remcostoeten/fync

Version:

A unified TypeScript library for easy access to popular APIs (GitHub, Spotify, GitLab, etc.)

32 lines (31 loc) 864 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.memoize = memoize; function memoize(fn, getKey, options = {}) { const cache = new Map(); function memoizedFunction(...args) { const key = getKey ? getKey(...args) : JSON.stringify(args); const now = Date.now(); const cached = cache.get(key); if (cached && (!options.ttl || now - cached.timestamp < options.ttl)) { return cached.value; } const result = fn(...args); cache.set(key, { value: result, timestamp: now }); if (options.ttl) { setTimeout(function cleanupExpiredEntry() { const entry = cache.get(key); if (entry && options.ttl && now - entry.timestamp >= options.ttl) { cache.delete(key); } }, options.ttl); } return result; } return memoizedFunction; }