@stringsync/vexml
Version:
MusicXML to Vexflow
46 lines (45 loc) • 1.35 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LRU = void 0;
/**
* Represents a least-recently-used (LRU) cache.
*
* When at capacity, this cache will evict the least recently used key-value pair. This is particularly useful if you
* don't intend a cache to grow in size indefinitely.
*/
class LRU {
capacity;
map;
constructor(capacity) {
this.capacity = capacity;
this.map = new Map();
}
/** Returns the value corresponding to the key, if it exists. Defaults to null. */
get(key) {
let value = null;
if (this.has(key)) {
value = this.map.get(key);
this.map.delete(key);
this.map.set(key, value);
}
return value;
}
/** Puts the key-value pair, updating how recently "used" a key was used if applicable. */
put(key, value) {
if (this.map.has(key)) {
this.map.delete(key);
}
this.map.set(key, value);
if (this.map.size > this.capacity) {
const { value } = this.map.entries().next();
if (typeof value !== 'undefined') {
this.map.delete(value[0]);
}
}
}
/** Returns whether the key is in the cache. */
has(key) {
return this.map.has(key);
}
}
exports.LRU = LRU;