{"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,KAAiB;CACnC,IAAI;CACJ,IAAI;CAEJ,MAAM,SAAS,UAAgB;AAC7B,MAAI,CAAC,MAAM,KAAM;AACjB,MAAI,CAAC,MAAM,MAAM;AACf,SAAM,KAAK,OAAO,KAAA;AAClB,YAAS,MAAM;AACf,SAAM,OAAO,KAAA;AACb,OAAI,QAAQ;AACV,UAAM,OAAO;AACb,WAAO,OAAO;;SAEX;AACL,SAAM,KAAK,OAAO,MAAM;AACxB,SAAM,KAAK,OAAO,MAAM;AACxB,SAAM,OAAO,KAAA;AACb,OAAI,QAAQ;AACV,WAAO,OAAO;AACd,UAAM,OAAO;;;AAGjB,WAAS;;AAGX,QAAO;EACL,IAAI,KAAK;GACP,MAAM,QAAQ,MAAM,IAAI,IAAI;AAC5B,OAAI,CAAC,MAAO,QAAO,KAAA;AACnB,SAAM,MAAM;AACZ,UAAO,MAAM;;EAEf,IAAI,KAAK,OAAO;AACd,OAAI,MAAM,QAAQ,OAAO,QAAQ;IAC/B,MAAM,WAAW;AACjB,UAAM,OAAO,SAAS,IAAI;AAC1B,QAAI,SAAS,MAAM;AACjB,cAAS,SAAS;AAClB,cAAS,KAAK,OAAO,KAAA;;AAEvB,QAAI,aAAa,OACf,UAAS,KAAA;;GAGb,MAAM,WAAW,MAAM,IAAI,IAAI;AAC/B,OAAI,UAAU;AACZ,aAAS,QAAQ;AACjB,UAAM,SAAS;UACV;IACL,MAAM,QAAc;KAAE;KAAK;KAAO,MAAM;KAAQ;AAChD,QAAI,OAAQ,QAAO,OAAO;AAC1B,aAAS;AACT,QAAI,CAAC,OAAQ,UAAS;AACtB,UAAM,IAAI,KAAK,MAAM;;;EAGzB,QAAQ;AACN,SAAM,OAAO;AACb,YAAS,KAAA;AACT,YAAS,KAAA;;EAEZ"}