osrs-tools
Version:
A comprehensive TypeScript library for Old School RuneScape (OSRS) data and utilities, including quest data, skill requirements, and game item information
127 lines • 3.5 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cache = void 0;
/**
* Generic cache implementation with LRU eviction and TTL support
*/
class Cache {
/**
* Creates a new Cache instance
* @param options Cache configuration options
*/
constructor(options = {}) {
this.store = new Map();
this.maxSize = options.maxSize || 100;
this.ttl = options.ttl;
}
/**
* Store a value in the cache
* @param key Cache key
* @param value Value to store
* @param ttl Optional TTL override for this item
*/
set(key, value, ttl) {
// Enforce size limit using LRU eviction
if (this.store.size >= this.maxSize) {
const firstKey = this.store.keys().next().value;
this.store.delete(firstKey);
}
const expiresAt = ttl || this.ttl ? Date.now() + (ttl || this.ttl) : undefined;
this.store.set(key, { value, expiresAt });
}
/**
* Retrieve a value from the cache
* @param key Cache key
* @returns Stored value or undefined if not found/expired
*/
get(key) {
const item = this.store.get(key);
if (!item) {
return undefined;
}
// Check if item has expired
if (item.expiresAt && Date.now() > item.expiresAt) {
this.store.delete(key);
return undefined;
}
return item.value;
}
/**
* Remove an item from the cache
* @param key Cache key
* @returns true if item was found and removed
*/
delete(key) {
return this.store.delete(key);
}
/**
* Clear all items from the cache
*/
clear() {
this.store.clear();
}
/**
* Get the number of items in the cache
*/
get size() {
return this.store.size;
}
/**
* Get all valid keys in the cache
* @returns Array of cache keys
*/
keys() {
const now = Date.now();
return Array.from(this.store.entries())
.filter(([_, item]) => !item.expiresAt || item.expiresAt > now)
.map(([key]) => key);
}
/**
* Remove all expired items from the cache
* @returns Number of items removed
*/
prune() {
const now = Date.now();
let removed = 0;
for (const [key, item] of this.store.entries()) {
if (item.expiresAt && item.expiresAt <= now) {
this.store.delete(key);
removed++;
}
}
return removed;
}
/**
* Check if a key exists in the cache and isn't expired
* @param key Cache key
* @returns true if key exists and isn't expired
*/
has(key) {
const item = this.store.get(key);
if (!item) {
return false;
}
if (item.expiresAt && Date.now() > item.expiresAt) {
this.store.delete(key);
return false;
}
return true;
}
/**
* Get or set a cache value
* @param key Cache key
* @param factory Function to create value if not found
* @returns Cached or newly created value
*/
async getOrSet(key, factory) {
const existing = this.get(key);
if (existing !== undefined) {
return existing;
}
const value = await factory();
this.set(key, value);
return value;
}
}
exports.Cache = Cache;
//# sourceMappingURL=cache.js.map