ai-patterns
Version:
Production-ready TypeScript patterns to build solid and robust AI applications. Retry logic, circuit breakers, rate limiting, human-in-the-loop escalation, prompt versioning, response validation, context window management, and more—all with complete type
37 lines • 1.23 kB
JavaScript
;
/**
* Memoize Pattern - Cache function results
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.memoize = memoize;
const common_1 = require("../types/common");
function memoize(options) {
const { execute: fn, ttl, keyFn = (...args) => JSON.stringify(args), logger = common_1.defaultLogger, onCacheHit, onCacheMiss, } = options;
const cache = new Map();
const memoized = async function (...args) {
const key = keyFn(...args);
const now = Date.now();
// Check cache
const cached = cache.get(key);
if (cached && cached.expiresAt > now) {
if (onCacheHit)
onCacheHit(key);
logger.info(`Cache hit: ${key}`);
return cached.value;
}
// Cache miss
if (onCacheMiss)
onCacheMiss(key);
logger.info(`Cache miss: ${key}`);
const value = await fn(...args);
const expiresAt = ttl ? now + ttl : Infinity;
cache.set(key, { value, expiresAt });
return value;
};
// Add clear method to the function
memoized.clear = () => {
cache.clear();
};
return memoized;
}
//# sourceMappingURL=memoize.js.map