Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @param {number} capacity
- */
- var LFUCache = function(capacity) {
- this.recent = 0;
- this.storage = {};
- this.setCap = capacity;
- };
- LFUCache.prototype.get = function(key) {
- if(this.storage[key]){
- this.storage[key].recent = this.recent
- this.recent ++
- this.storage[key].frequency = this.storage[key].frequency + 1
- return this.storage[key].value
- } else {
- return -1
- }
- };
- LFUCache.prototype.put = function(key, val) {
- if(Object.keys(this.storage).length === this.setCap && !this.storage[key]){
- leastFrequency = [Infinity]
- for(var keys in this.storage){
- if(this.storage[keys].frequency < leastFrequency[0]){
- leastFrequency = [this.storage[keys].frequency, keys]
- } else if(this.storage[keys].frequency === leastFrequency[0]){
- console.log(keys, leastFrequency)
- this.storage[keys].recent < this.storage[leastFrequency[1]].recent ? leastFrequency = [this.storage[keys].frequency, keys] : null
- }
- }
- delete this.storage[leastFrequency[1]]
- }
- if(this.setCap !== 0){
- this.storage[key] = {
- value: val,
- frequency: 0,
- recent: this.recent
- }
- }
- this.recent ++
- };
Add Comment
Please, Sign In to add comment