Skip to content
Snippets Groups Projects
Select Git revision
  • 524ed90e3f26205f42aaefd6cd5a3ef4144eedd4
  • master default protected
  • rednatco-v2
  • rednatco
  • test
  • ntc-tube-uniform-color
  • ntc-tube-missing-atoms
  • restore-vertex-array-per-program
  • watlas2
  • dnatco_new
  • cleanup-old-nodejs
  • webmmb
  • fix_auth_seq_id
  • update_deps
  • ext_dev
  • ntc_balls
  • nci-2
  • plugin
  • bugfix-0.4.5
  • nci
  • servers
  • v0.5.0-dev.1
  • v0.4.5
  • v0.4.4
  • v0.4.3
  • v0.4.2
  • v0.4.1
  • v0.4.0
  • v0.3.12
  • v0.3.11
  • v0.3.10
  • v0.3.9
  • v0.3.8
  • v0.3.7
  • v0.3.6
  • v0.3.5
  • v0.3.4
  • v0.3.3
  • v0.3.2
  • v0.3.1
  • v0.3.0
41 results

lru-cache.ts

Blame
  • user avatar
    Alexander Rose authored
    524ed90e
    History
    lru-cache.ts 1.43 KiB
    
    /**
     * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
     *
     * Adapted from LiteMol.
     * @author David Sehnal <david.sehnal@gmail.com>
     */
    
    import { LinkedList } from '../mol-data/generic';
    
    export { LRUCache };
    
    interface LRUCache<T> {
        entries: LinkedList<LRUCache.Entry<T>>,
        capacity: number
    }
    
    namespace LRUCache {
        export interface Entry<T> {
            key: string,
            data: T
        }
    
        function entry<T>(key: string, data: T): Entry<T> {
            return { key, data };
        }
    
        export function create<T>(capacity: number): LRUCache<T> {
            return {
                entries: LinkedList<Entry<T>>(),
                capacity: Math.max(1, capacity)
            };
        }
    
        export function get<T>(cache: LRUCache<T>, 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<T>(cache: LRUCache<T>, key: string, data: T): T | undefined {
            let removed: T | undefined = undefined;
            if (cache.entries.count >= cache.capacity) {
                const first = cache.entries.first!;
                removed = first.value.data;
                cache.entries.remove(first);
            }
            cache.entries.addLast(entry(key, data));
            return removed;
        }
    }