@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
103 lines (93 loc) • 2.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MapAsyncMemoCache = exports.MapMemoCache = exports.jsonMemoSerializer = void 0;
const is_util_1 = require("../is.util");
const pDelay_1 = require("../promise/pDelay");
const types_1 = require("../types");
const jsonMemoSerializer = args => {
if (args.length === 0)
return undefined;
if (args.length === 1 && (0, is_util_1._isPrimitive)(args[0]))
return args[0];
return JSON.stringify(args);
};
exports.jsonMemoSerializer = jsonMemoSerializer;
// 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 = {}
}
}
*/
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();
}
}
exports.MapMemoCache = MapMemoCache;
/**
* 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.
*/
class MapAsyncMemoCache {
delay;
constructor(delay = 0) {
this.delay = delay;
}
m = new Map();
async get(k) {
await (0, pDelay_1.pDelay)(this.delay);
if (!this.m.has(k))
return types_1.MISS;
return this.m.get(k);
}
async set(k, v) {
await (0, pDelay_1.pDelay)(this.delay);
this.m.set(k, v);
}
async clear() {
await (0, pDelay_1.pDelay)(this.delay);
this.m.clear();
}
}
exports.MapAsyncMemoCache = MapAsyncMemoCache;