{"version":3,"file":"lru-cache.cjs","names":[],"sources":["../../src/lru-cache.ts"],"sourcesContent":["export type LRUCache<TKey, TValue> = {\n  get: (key: TKey) => TValue | undefined\n  set: (key: TKey, value: TValue) => void\n  clear: () => void\n}\n\nexport function createLRUCache<TKey, TValue>(\n  max: number,\n): LRUCache<TKey, TValue> {\n  type Node = { prev?: Node; next?: Node; key: TKey; value: TValue }\n  const cache = new Map<TKey, Node>()\n  let oldest: Node | undefined\n  let newest: Node | undefined\n\n  const touch = (entry: Node) => {\n    if (!entry.next) return\n    if (!entry.prev) {\n      entry.next.prev = undefined\n      oldest = entry.next\n      entry.next = undefined\n      if (newest) {\n        entry.prev = newest\n        newest.next = entry\n      }\n    } else {\n      entry.prev.next = entry.next\n      entry.next.prev = entry.prev\n      entry.next = undefined\n      if (newest) {\n        newest.next = entry\n        entry.prev = newest\n      }\n    }\n    newest = entry\n  }\n\n  return {\n    get(key) {\n      const entry = cache.get(key)\n      if (!entry) return undefined\n      touch(entry)\n      return entry.value\n    },\n    set(key, value) {\n      if (cache.size >= max && oldest) {\n        const toDelete = oldest\n        cache.delete(toDelete.key)\n        if (toDelete.next) {\n          oldest = toDelete.next\n          toDelete.next.prev = undefined\n        }\n        if (toDelete === newest) {\n          newest = undefined\n        }\n      }\n      const existing = cache.get(key)\n      if (existing) {\n        existing.value = value\n        touch(existing)\n      } else {\n        const entry: Node = { key, value, prev: newest }\n        if (newest) newest.next = entry\n        newest = entry\n        if (!oldest) oldest = entry\n        cache.set(key, entry)\n      }\n    },\n    clear() {\n      cache.clear()\n      oldest = undefined\n      newest = undefined\n    },\n  }\n}\n"],"mappings":";AAMA,SAAgB,eACd,KACwB;CAExB,MAAM,wBAAQ,IAAI,IAAgB;CAClC,IAAI;CACJ,IAAI;CAEJ,MAAM,SAAS,UAAgB;EAC7B,IAAI,CAAC,MAAM,MAAM;EACjB,IAAI,CAAC,MAAM,MAAM;GACf,MAAM,KAAK,OAAO,KAAA;GAClB,SAAS,MAAM;GACf,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