/** * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info. * * Adapted from LiteMol. * @author David Sehnal */ import { LinkedList } from '../mol-data/generic'; export { LRUCache } interface LRUCache { entries: LinkedList>, capacity: number } namespace LRUCache { export interface Entry { key: string, data: T } function entry(key: string, data: T): Entry { return { key, data }; } export function create(capacity: number): LRUCache { return { entries: LinkedList>(), capacity: Math.max(1, capacity) }; } export function get(cache: LRUCache, key: string) { for (let e = cache.entries.first; e; e = e.next) { if (e.value.key === key) { cache.entries.remove(e); cache.entries.addLast(e.value); return e.value.data; } } return void 0; } export function set(cache: LRUCache, key: string, data: T): T { if (cache.entries.count >= cache.capacity) { cache.entries.remove(cache.entries.first!); } cache.entries.addLast(entry(key, data)); return data; } }