Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. var LFUCache = function(capacity) {
  2. this.storage = {};
  3. this.capacity = capacity;
  4. this.history = [];
  5. this.usage = 0;
  6. };
  7.  
  8. LFUCache.prototype.get = function(key) {
  9. // check if key exists on this.storage
  10. if (this.storage[key]) {
  11. // if so, increment frequency by 1
  12. this.storage[key].frequency += 1;
  13. // push to this.history
  14. this.history.push(key);
  15. return this.storage[key].value;
  16. }
  17. return -1;
  18. };
  19.  
  20. LFUCache.prototype.put = function(key, value) {
  21. // check if we have reached capacity Object.keys(this.storage).length
  22. if (Object.keys(this.storage).length === this.capacity) {
  23. let frequency;
  24. let least;
  25. let tiebreaker = [];
  26. // for each key in this.storage
  27. for (let key in this.storage) {
  28. if (!frequency) {
  29. frequency = this.storage[key].frequency;
  30. }
  31. if (this.storage[key].frequency < frequency) {
  32. frequency = this.storage[key].frequency;
  33. least = key;
  34. }
  35. }
  36. for (let key in this.storage) {
  37. if (this.storage[key].frequency === frequency) {
  38. tiebreaker.push(key);
  39. }
  40. }
  41. delete this.storage[least];
  42. }
  43. };
  44.  
  45. // the put function
  46. // check the capacity: has it been reached?
  47. // if it hasn't, we can add it to an object called storage, with frequency of 0
  48. // if we have reached the capacity, we remove the least used key using for/in
  49. // if there's a tie, then we loop through history and remove the first key we encounter
  50. // then we add the kv pair
  51.  
  52. /**
  53. * Your LFUCache object will be instantiated and called as such:
  54. * var obj = Object.create(LFUCache).createNew(capacity)
  55. * var param_1 = obj.get(key)
  56. * obj.put(key,value)
  57. */
  58.  
  59. // get inputs: key
  60. // get output: value, or -1 if does not exist
  61.  
  62. // put: key and value
  63. // output: return the value
  64.  
  65. // constraints: values in puts will always be positive
  66. // keep track of how many times each kv pair has been accessed
  67. // kv pair: key: {value: x, frequency: x}
  68. // array, call it history: [key1, key2, key3]
  69.  
  70. // the get function
  71. // look up the key
  72. // if it exists return the value
  73. // increment frequency by 1
  74. // push the key to the history array
  75. // if it doesn't exist, return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement