UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

97 lines (87 loc) 1.88 kB
import { _isPrimitive } from '../is.util.js'; import { pDelay } from '../promise/pDelay.js'; import { MISS } from '../types.js'; export const jsonMemoSerializer = args => { if (args.length === 0) return undefined; if (args.length === 1 && _isPrimitive(args[0])) return args[0]; return JSON.stringify(args); }; // SingleValueMemoCache and ObjectMemoCache are example-only, not used in production code /* export class SingleValueMemoCache implements MemoCache { private v: any = undefined private valueSet = false has() { return this.valueSet } get() { return this.v } set(_k: any, _v: any) { this.v = _v this.valueSet = true } clear() { this.valueSet = false } } export class ObjectMemoCache implements MemoCache { private v = {} has(k: any) { return k in this.v // return this.v[k] } get(k: any) { return this.v[k] } set(k: any, v: any) { this.v[k] = v } clear() { this.v = {} } } */ export class MapMemoCache { m = new Map(); has(k) { return this.m.has(k); } get(k) { return this.m.get(k); } set(k, v) { this.m.set(k, v); } clear() { this.m.clear(); } } /** * Implementation of AsyncMemoCache backed by a synchronous Map. * Doesn't have a practical use except testing, * because the point of AsyncMemoCache is to have an **async** backed cache. */ export class MapAsyncMemoCache { delay; constructor(delay = 0) { this.delay = delay; } m = new Map(); async get(k) { await pDelay(this.delay); if (!this.m.has(k)) return MISS; return this.m.get(k); } async set(k, v) { await pDelay(this.delay); this.m.set(k, v); } async clear() { await pDelay(this.delay); this.m.clear(); } }