simple-node-memory-cache
Version:
In-memory object cache written in typescript for Node that supports multiple eviction strategies.
89 lines (88 loc) • 3.46 kB
JavaScript
;
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __values = (this && this.__values) || function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
var Cache_1 = require("../cacheBase/Cache");
var SimpleLFU = /** @class */ (function (_super) {
__extends(SimpleLFU, _super);
function SimpleLFU() {
return _super !== null && _super.apply(this, arguments) || this;
}
SimpleLFU.prototype.get = function (key) {
return this.update(key, this.cache.get(key));
};
SimpleLFU.prototype.set = function (key, value) {
var e_1, _a;
if (this.cache.size >= this._maxObjectsInCache && !this.cache.has(key)) {
// Find the least recently used.
var leastFrequentlyUsedKey = undefined;
var lowestEntry = undefined;
try {
for (var _b = __values(this.cache.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), key_1 = _d[0], value_1 = _d[1];
if (value_1[2] < lowestEntry || lowestEntry === undefined) {
lowestEntry = value_1[2];
leastFrequentlyUsedKey = key_1;
}
// If 0 then break as lower is not possible.
if (lowestEntry === 0) {
break;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
// And delete it.
this.cache.delete(leastFrequentlyUsedKey);
}
return this.cache.set(key, [value, 0, 0]);
};
SimpleLFU.prototype.update = function (key, value) {
this.cache.set(key, [value[0], 0, value[2] + 1]);
return [value[0], 0, value[2] + 1];
};
return SimpleLFU;
}(Cache_1.SimpleCache));
exports.SimpleLFU = SimpleLFU;