UNPKG

simple-node-memory-cache

Version:

In-memory object cache written in typescript for Node that supports multiple eviction strategies.

86 lines (85 loc) 3.31 kB
"use strict"; 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 SimpleMRU = /** @class */ (function (_super) { __extends(SimpleMRU, _super); function SimpleMRU() { return _super !== null && _super.apply(this, arguments) || this; } SimpleMRU.prototype.get = function (key) { return this.update(key, this.cache.get(key)); }; SimpleMRU.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 leastRecentlyUsedKey = undefined; var oldestEntry = 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[1] > oldestEntry || oldestEntry === undefined) { oldestEntry = value_1[1]; leastRecentlyUsedKey = key_1; } } } 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(leastRecentlyUsedKey); } return this.cache.set(key, [value, Date.now(), 0]); }; SimpleMRU.prototype.update = function (key, value) { var read = Date.now(); this.cache.set(key, [value[0], read, 0]); return [value[0], read, 0]; }; return SimpleMRU; }(Cache_1.SimpleCache)); exports.SimpleMRU = SimpleMRU;