r3bl-ts-utils
Version:
The `r3bl-ts-utils` package is a set of useful TypeScript functions and classes that can be used in Node.js and browser environments. They are inspired by Kotlin stdlib, and Rust to write code as expressions rather than statements, colorized text, powerfu
81 lines • 3.36 kB
JavaScript
/*
* Copyright (c) 2022 R3BL LLC. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Analytics = void 0;
const kotlin_lang_utils_1 = require("../lang-utils/kotlin-lang-utils");
const debug_1 = require("./debug");
// eslint-disable-next-line
var Analytics;
(function (Analytics) {
// Exposed outside of namespace.
Analytics.createInstance = () => new Impl();
// ENHANCEMENT Create more complex eviction & refresh policies w/ insertionTime & lastAccessTime
class Insight {
/* Num of times key was accessed, used to calculate popularity. */
accessCount = 1;
/* Time at which the key was inserted, used to calculate age. */
insertionTime = Date.now();
/* Time at which key was last accessed, used to calculate recency. */
lastAccessTime = Date.now();
}
Analytics.Insight = Insight;
// Hidden inside namespace.
class Impl {
heatmap = new Map();
evictions = 0;
update = (key) => {
const { heatmap: hm } = this;
hm.has(key)
? (0, kotlin_lang_utils_1._also)(hm.get(key), (hmEntry) => {
if (!hmEntry) {
// eslint-disable-next-line
throw new Error(`Cache entry for key ${key} should not be null / undefined!`);
}
hmEntry.accessCount++;
hmEntry.lastAccessTime = Date.now();
})
: (0, kotlin_lang_utils_1._also)(new Insight(), (it) => {
hm.set(key, it);
});
};
purge = (keyToDelete) => {
this.heatmap.delete(keyToDelete);
this.evictions++;
};
findLRUKey = (cache) => {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys
return cache._map.keys().next().value;
};
findLFUKey = () => {
let keyToDelete = undefined;
let minCount = undefined;
debug_1.DEBUG && console.log(this.heatmap);
for (const [key, insight] of this.heatmap.entries()) {
if (!minCount)
minCount = insight.accessCount;
if (insight.accessCount <= minCount)
keyToDelete = key;
debug_1.DEBUG && console.log("[findLFUKey]", key, "|", insight, "|", minCount, "|", keyToDelete);
}
if (!keyToDelete)
throw new Error("Could not find keyToDelete (can't be nullish) in Policy.findLFUKey!");
return keyToDelete;
};
}
})(Analytics = exports.Analytics || (exports.Analytics = {}));
//# sourceMappingURL=analytics.js.map
;