UNPKG

modrinth

Version:

JavaScript library for accessing the Modrinth API

70 lines (69 loc) 1.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Cache = void 0; class Cache { constructor(options = Object.create(null)) { this.options = {}; Object.assign(this.options, Cache.defaultOptions, options); this.data = Object.create(null); } get now() { return Date.now(); } get capacity() { return this.options.capacity; } get size() { return Object.keys(this.data).length; } get empty() { return this.size <= 0; } get full() { return this.size >= this.capacity; } get percent() { return (this.size / this.capacity) * 100; } get(key) { if (!this.data[key]) return; if (this.data[key].expiry >= Date.now()) { this.delete(key); return; } return this.data[key].value; } has(key) { return !!this.get(key); } set(key, value, ttl) { if (!ttl) ttl = this.options.ttl; if (this.full) this.prune(1); return this.data[key] = { expiry: this.now + ttl, value }; } prune(amount = 1) { /** the keys of the {amount} oldest items. */ const keys = Object.keys(this.data).splice(0, amount); for (const key in keys) { this.delete(key); } } delete(key) { if (this.data[key]) delete this.data[key]; } clear() { this.data = Object.create(null); } } exports.Cache = Cache; Cache.defaultOptions = { ttl: Infinity, capacity: Infinity };