Guest User

Untitled

a guest
Feb 21st, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. /**
  2. * @param {number} capacity
  3. */
  4. var LFUCache = function(capacity) {
  5. this.recent = 0;
  6. this.storage = {};
  7. this.setCap = capacity;
  8. };
  9.  
  10.  
  11. LFUCache.prototype.get = function(key) {
  12. if(this.storage[key]){
  13. this.storage[key].recent = this.recent
  14. this.recent ++
  15. this.storage[key].frequency = this.storage[key].frequency + 1
  16. return this.storage[key].value
  17. } else {
  18. return -1
  19. }
  20. };
  21.  
  22.  
  23. LFUCache.prototype.put = function(key, val) {
  24. if(Object.keys(this.storage).length === this.setCap && !this.storage[key]){
  25. leastFrequency = [Infinity]
  26. for(var keys in this.storage){
  27. if(this.storage[keys].frequency < leastFrequency[0]){
  28. leastFrequency = [this.storage[keys].frequency, keys]
  29. } else if(this.storage[keys].frequency === leastFrequency[0]){
  30. console.log(keys, leastFrequency)
  31. this.storage[keys].recent < this.storage[leastFrequency[1]].recent ? leastFrequency = [this.storage[keys].frequency, keys] : null
  32. }
  33. }
  34. delete this.storage[leastFrequency[1]]
  35. }
  36. if(this.setCap !== 0){
  37. this.storage[key] = {
  38. value: val,
  39. frequency: 0,
  40. recent: this.recent
  41. }
  42. }
  43. this.recent ++
  44. };
Add Comment
Please, Sign In to add comment