push
This commit is contained in:
1 parent
bcf05e8063
commit
f37985b4c8
109 files changed
+22810
-6143
No files matched your search
@@ -0,0 +1,88 @@
|
||||
// LRU + TTL map with in-flight promise dedupe.
|
||||
//
|
||||
// const c = createCache({ max: 500, ttlMs: 60_000 });
|
||||
// c.set(k, v, ttlMs?) c.get(k) c.has(k) c.delete(k)
|
||||
// await c.wrap(k, () => fetchThing(), ttlMs?)
|
||||
//
|
||||
// `wrap` returns the cached value if fresh, joins an in-flight call for the same key,
|
||||
// or runs `fn` and caches its resolved value. `ttlMs` may be a function of the value
|
||||
// (return 0 / falsy to skip caching, e.g. for error results). Rejections are never cached.
|
||||
|
||||
function createCache({ max = 1000, ttlMs = 60_000 } = {}) {
|
||||
const map = new Map(); // key -> { value, expires }; Map order = LRU order (oldest first)
|
||||
const inflight = new Map(); // key -> Promise
|
||||
|
||||
function get(key) {
|
||||
const hit = map.get(key);
|
||||
if (!hit) return undefined;
|
||||
if (hit.expires <= Date.now()) {
|
||||
map.delete(key);
|
||||
return undefined;
|
||||
}
|
||||
map.delete(key); // bump to most-recent
|
||||
map.set(key, hit);
|
||||
return hit.value;
|
||||
}
|
||||
|
||||
function has(key) {
|
||||
const hit = map.get(key);
|
||||
if (!hit) return false;
|
||||
if (hit.expires <= Date.now()) {
|
||||
map.delete(key);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function set(key, value, ttl = ttlMs) {
|
||||
if (!(ttl > 0)) return value;
|
||||
map.delete(key);
|
||||
map.set(key, { value, expires: Date.now() + ttl });
|
||||
while (map.size > max) map.delete(map.keys().next().value);
|
||||
return value;
|
||||
}
|
||||
|
||||
function del(key) {
|
||||
inflight.delete(key);
|
||||
return map.delete(key);
|
||||
}
|
||||
|
||||
function wrap(key, fn, ttl = ttlMs) {
|
||||
if (has(key)) return Promise.resolve(get(key));
|
||||
const pending = inflight.get(key);
|
||||
if (pending) return pending;
|
||||
const p = Promise.resolve()
|
||||
.then(fn)
|
||||
.then(
|
||||
(value) => {
|
||||
if (inflight.get(key) === p) inflight.delete(key);
|
||||
set(key, value, typeof ttl === 'function' ? ttl(value) : ttl);
|
||||
return value;
|
||||
},
|
||||
(err) => {
|
||||
if (inflight.get(key) === p) inflight.delete(key);
|
||||
throw err;
|
||||
}
|
||||
);
|
||||
inflight.set(key, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
return {
|
||||
get,
|
||||
set,
|
||||
has,
|
||||
delete: del,
|
||||
wrap,
|
||||
inflight: (key) => inflight.get(key),
|
||||
clear() {
|
||||
map.clear();
|
||||
inflight.clear();
|
||||
},
|
||||
get size() {
|
||||
return map.size;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createCache };
|
||||
Reference in new issue
Block a user