Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Text · 47 lines · 1.3 KiB · at 9dcde16

import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime";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.  const map = new Map<string, V>();  const touch = (key: string, value: V): Option<V> => {    map.delete(key);    map.set(key, value);    return Some(value);  };  const evictOldest = (): void => {    const oldest = map.keys().next();    if (!oldest.done) {      map.delete(oldest.value);    }  };  return {    get: (key) => (map.has(key) ? touch(key, map.get(key) as V) : None),    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" });