namespace drunk { interface ICacheNode { prev : ICacheNode ; next : ICacheNode ; key : string ; value : any ; } /**
     * LRU Cache类
     */ export class Cache < T > { /**
         * 缓存节点的hash表
         */ private _cacheMap : { [ key ] : ICacheNode ; } = { } ; /**
         * 缓存头部
         */ private _head : ICacheNode = null ; /**
         * 缓存尾部
         */ private _tail : ICacheNode = null ; /**
         * 缓存容量
         */ private _capacity : number ; /**
         * 缓存节点计数
         */ private _count : number = 0 ; param capacity constructor ( capacity ) { if ( capacity < 1 ) { throw new Error ( `缓存容量必须大于0` ) ; } this . _capacity = capacity ; } param key get ( key ) { let cacheNode = this . _cacheMap [ key ] ; if ( ! cacheNode ) { return ; } this . _putToHead ( cacheNode ) ; return cacheNode . value ; } param key param value set ( key , value ) { let cacheNode = this . _cacheMap [ key ] ; if ( cacheNode ) { cacheNode . value = value ; } else { cacheNode = this . _cacheMap [ key ] = { prev : null , next : null , key : key , value : value } ; if ( this . _count < this . _capacity ) { this . _putToHead ( cacheNode ) ; this . _count += 1 ; } else { this . _putToHead ( cacheNode ) ; this . _removeTail ( ) ; } } } param cacheNode private _putToHead ( cacheNode ) { if ( cacheNode === this . _head ) { return ; } if ( cacheNode . prev != null ) { cacheNode . prev . next = cacheNode . next ; } if ( cacheNode . next != null ) { cacheNode . next . prev = cacheNode . prev ; } if ( this . _tail === cacheNode ) { this . _tail = cacheNode . prev ; } cacheNode . prev = null ; cacheNode . next = this . _head ; if ( this . _head ) { this . _head . prev = cacheNode ; } else { this . _tail = cacheNode ; } this . _head = cacheNode ; } return private _removeTail ( ) { let tail = this . _tail ; this . _tail = tail . prev ; tail . prev . next = tail . next ; tail . prev = null ; tail . next = null ; delete this . _cacheMap [ tail . key ] ; } } }