package { /*@Author - Gaurav Pandey @Description - Part of a Flex-Collection API*/ public class LRUCache { [Bindable] public var dict : MyDictionary = null; [Bindable] public var list : MyLinkedList = null; [Bindable] private var maxCacheSizeLimit : int = 0; public function LRUCache(maxCacheSize : int = 10) : void { dict = new MyDictionary(); list = new MyLinkedList(); this.maxCacheSizeLimit = maxCacheSize; } public function insertInCache(keyvalue : Object) : void { if(this == null) throw new ReferenceError("Object instance is null"); if(!(this is LRUCache)) throw new MDIllegalObjectException("Object referenced is not a LRUCache"); if(keyvalue == null) throw new ArgumentError("Object is Null"); var node : MyNode = null; if(dict.containsKey(keyvalue)) { var tempNode : MyNode = dict.getValue(keyvalue) as MyNode; if(tempNode.next != null) tempNode.next.prev = tempNode.prev; if(tempNode.prev != null) tempNode.prev.next = tempNode.next; tempNode.next = null; tempNode.prev = null; dict.removeKey(keyvalue); } else if(dict.getSize() == maxCacheSizeLimit) removeCacheElement(); dict.insertKey(keyvalue, list.insertAtStartLRU(keyvalue, keyvalue)); } public function insertKeyInCache(key : Object, value : Object) : void { if(this == null) throw new ReferenceError("Object instance is null"); if(!(this is LRUCache)) throw new MDIllegalObjectException("Object referenced is not a LRUCache"); if(key == null) throw new ArgumentError("Key is Null"); if(value == null) throw new ArgumentError("Value is Null"); var node : MyNode = null; if(dict.containsKey(key)) { var tempNode : MyNode = dict.getValue(key) as MyNode; if(tempNode.next != null) tempNode.next.prev = tempNode.prev; if(tempNode.prev != null) tempNode.prev.next = tempNode.next; tempNode.next = null; tempNode.prev = null; dict.removeKey(key); } else if(dict.getSize() == maxCacheSizeLimit) removeCacheElement(); dict.insertKey(key, list.insertAtStartLRU(key, value)); } public function removeCacheElement() : void { dict.removeKey(list.removeAtEnd().key); } public function getData(key : Object) : Object { if(this == null) throw new ReferenceError("Object instance is null"); if(!(this is LRUCache)) throw new MDIllegalObjectException("Object referenced is not a LRUCache"); if(key == null) throw new ArgumentError("Key is Null"); var node : MyNode = null; if(dict.containsKey(key)) { return (dict.getValue(key) as MyNode).data; } else { trace("Key does not exist"); return null; } } public function clearCache() : void { if(this == null) throw new ReferenceError("Object instance is null"); if(!(this is LRUCache)) throw new MDIllegalObjectException("Object referenced is not a LRUCache"); } public function getCacheSize() : int { if(this == null) throw new ReferenceError("Object instance is null"); if(!(this is LRUCache)) throw new MDIllegalObjectException("Object referenced is not a LRUCache"); return dict.getSize(); } } }