import { Some, Ok, Err, type Option, type Result } from "@tsus/runtime";import { fromNullable } from "@tsus/runtime/boundary";export type LruError = { kind: "invalid_capacity" };export type Lru<V> = { get: (key: string) => Option<V>; set: (key: string, value: V) => void; delete: (key: string) => boolean; size: () => number; keys: () => string[];};const build = <V>(capacity: number): Lru<V> => { // Map iteration order is insertion order: oldest first, newest last. // Values are boxed so a stored falsy value still counts as present. const map = new Map<string, { value: V }>(); const touch = (key: string, box: { value: V }): Option<V> => { map.delete(key); map.set(key, box); return Some(box.value); }; const evictOldest = (): void => { const oldest = map.keys().next(); if (!oldest.done) { map.delete(oldest.value); } }; return { get: (key) => fromNullable(map.get(key)).andThen((box) => touch(key, box)), set: (key, value) => { if (capacity === 0) { return; } if (map.has(key)) { map.delete(key); } else if (map.size >= capacity) { evictOldest(); } map.set(key, { value }); }, delete: (key) => map.delete(key), size: () => map.size, keys: () => [...map.keys()].reverse(), };};export const createLru = <V>(capacity: number): Result<Lru<V>, LruError> => Number.isInteger(capacity) && capacity >= 0 ? Ok(build<V>(capacity)) : Err({ kind: "invalid_capacity" });