Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @param {number} capacity
- */
- Object.size = function(obj) {
- var size = 0, key;
- for (key in obj) {
- if (obj.hasOwnProperty(key)) size++;
- }
- return size;
- };
- var LFUCache = function(capacity) {
- this.holdValue = capacity
- this.capacity = {}
- this.frequency = {}
- };
- /**
- * @param {number} key
- * @return {number}
- */
- LFUCache.prototype.get = function(key) {
- this.frequency[key]++
- if (this.capacity[key]===undefined) {
- return -1;
- }
- return this.capacity[key].key
- };
- /**
- * @param {number} key
- * @param {number} value
- * @return {void}
- */
- LFUCache.prototype.put = function(key, value) {
- var size = Object.size(this.capacity)
- if (size > this.holdValue - 1){
- var smallest = 999;
- var countKey = '';
- for (let keys in this.frequency) {
- if(this.frequency[keys] < smallest) {
- smallest = this.frequency[keys]
- countKey = keys
- }
- }
- delete this.frequency[countKey];
- delete this.capacity[countKey];
- }
- this.capacity[key] = {key: value}
- this.frequency[key] = 0
- };
- /**
- * Your LFUCache object will be instantiated and called as such:
- * var obj = Object.create(LFUCache).createNew(capacity)
- * var param_1 = obj.get(key)
- * obj.put(key,value)
- */
- var cache = new LFUCache(2);
- cache.put(1, 1);
- cache.put(2, 2);
- console.log(cache.get(1)); // returns 1
- cache.put(3, 3); // evicts key 2
- console.log(cache.get(2)); // returns -1 (not found)
- console.log(cache.get(3)); // returns 3.
- cache.put(4, 4); // evicts key 1.
- console.log(cache.get(1)); // returns -1 (not found)
- console.log(cache.get(3)); // returns 3
- console.log(cache.get(4)); // returns 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement