lru-cache.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * Adapted from LiteMol.
  5. * @author David Sehnal <david.sehnal@gmail.com>
  6. */
  7. import { LinkedList } from 'mol-data/generic';
  8. export { LRUCache }
  9. interface LRUCache<T> {
  10. entries: LinkedList<LRUCache.Entry<T>>,
  11. capacity: number
  12. }
  13. namespace LRUCache {
  14. export interface Entry<T> {
  15. key: string,
  16. data: T
  17. }
  18. function entry<T>(key: string, data: T): Entry<T> {
  19. return { key, data };
  20. }
  21. export function create<T>(capacity: number): LRUCache<T> {
  22. return {
  23. entries: LinkedList<Entry<T>>(),
  24. capacity: Math.max(1, capacity)
  25. };
  26. }
  27. export function get<T>(cache: LRUCache<T>, key: string) {
  28. for (let e = cache.entries.first; e; e = e.next) {
  29. if (e.value.key === key) {
  30. cache.entries.remove(e);
  31. cache.entries.addLast(e.value);
  32. return e.value.data;
  33. }
  34. }
  35. return void 0;
  36. }
  37. export function set<T>(cache: LRUCache<T>, key: string, data: T): T {
  38. if (cache.entries.count >= cache.capacity) {
  39. cache.entries.remove(cache.entries.first!);
  40. }
  41. cache.entries.addLast(entry(key, data));
  42. return data;
  43. }
  44. }