UNPKG

lincd

Version:

LINCD is a JavaScript library for building user interfaces with linked data (also known as 'structured data', or RDF)

62 lines 1.77 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.cached = void 0; const Shape_js_1 = require("../shapes/Shape.js"); const models_js_1 = require("../models.js"); const _cache = new Map(); /** * Caches the result of a function call based on its arguments for a specified time. * Arguments are converted to strings for comparison. * Use cacheTimeMs = 0 to disable caching. * Use cacheTimeMs = Infinity to never expire the cache. * @param fn * @param args * @param cacheTimeMs * @param alsoCacheErrors */ function cached(fn, args, cacheTimeMs, alsoCacheErrors) { if (cacheTimeMs !== 0) { const now = Date.now(); args = args.map((a) => { if (a instanceof Shape_js_1.Shape) { return a.uri; } else if (a instanceof models_js_1.NamedNode) { return a.uri; } else { return a === null || a === void 0 ? void 0 : a.toString(); } }); let key = JSON.stringify(args); let cache = _cache.get(key); if (cache && cache.timeout < now) { _cache.delete(key); cache = null; } if (!cache) { let value; try { value = fn(); } catch (e) { if (alsoCacheErrors) { value = e; } else { throw e; } } _cache.set(key, { timeout: now + cacheTimeMs, value, }); } return _cache.get(key).value; } else { return fn(); } } exports.cached = cached; //# sourceMappingURL=cached.js.map