UNPKG

@m4x1m1l14n/cache

Version:

Lightweight in-memory isomorphic cache implementation with TTL for browser & Node JS written in TypeScript

118 lines 3.23 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Cache = void 0; const helpers_1 = require("../helpers"); const detect_node_1 = __importDefault(require("detect-node")); class Cache { options; cache = new Map(); constructor(options) { this.options = { ...{ maxItems: 1000, resolution: 1000, // Default timeout is infinity defaultTTL: Number.POSITIVE_INFINITY, }, ...(options ?? {}), }; if (detect_node_1.default) { const interval = setInterval(() => this.cleanup(), this.options.resolution); interval.unref(); } else { window.setInterval(() => this.cleanup(), this.options.resolution); } } set(key, value, ttl, callback) { const now = (0, helpers_1.getMilliseconds)(); const wrapped = { created: now, value, ttl: ttl ?? this.options.defaultTTL, callback, }; this.cache.set(key, wrapped); return this; } /** * Returns value by its key * * @param key Key of value to get * @param refresh True to refresh item TTL or false to not */ get(key, refresh = false) { const wrapped = this.cache.get(key); if (wrapped) { if (refresh) { const now = (0, helpers_1.getMilliseconds)(); wrapped.created = now; } } return wrapped?.value; } /** * Takes value by its key from cache. * * Value is returned and key is removed from cache. * * @param key Key to take * @returns Value of specified key */ take(key) { const value = this.get(key); if (value !== undefined) { this.delete(key); } return value; } has(key) { return this.cache.has(key); } delete(key) { return this.cache.delete(key); } mdelete(keys) { for (const key of keys) { this.delete(key); } return this; } get size() { return this.cache.size; } forEach(cb) { this.cache.forEach((value, key) => { cb(value.value, key); }); } cleanup() { if (this.cache.size === 0) { return; } const now = (0, helpers_1.getMilliseconds)(); for (const [key, value] of this.cache) { if (now > value.created + value.ttl) { this.cache.delete(key); if (value.callback) { value.callback(value.value); } } } } flush(invokeCallback = false) { if (invokeCallback) { for (const [, value] of this.cache) { if (value.callback) { value.callback(value.value); } } } this.cache.clear(); } } exports.Cache = Cache; //# sourceMappingURL=Cache.js.map