Advertisement
Guest User

Untitled

a guest
Jul 28th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. /**
  2. * @param {number} capacity
  3. */
  4. Object.size = function(obj) {
  5. var size = 0, key;
  6. for (key in obj) {
  7. if (obj.hasOwnProperty(key)) size++;
  8. }
  9. return size;
  10. };
  11.  
  12. var LFUCache = function(capacity) {
  13. this.holdValue = capacity
  14. this.capacity = {}
  15. this.frequency = {}
  16. };
  17.  
  18. /**
  19. * @param {number} key
  20. * @return {number}
  21. */
  22. LFUCache.prototype.get = function(key) {
  23. this.frequency[key]++
  24. if (this.capacity[key]===undefined) {
  25. return -1;
  26. }
  27. return this.capacity[key].key
  28. };
  29.  
  30. /**
  31. * @param {number} key
  32. * @param {number} value
  33. * @return {void}
  34. */
  35. LFUCache.prototype.put = function(key, value) {
  36. var size = Object.size(this.capacity)
  37. if (size > this.holdValue - 1){
  38. var smallest = 999;
  39. var countKey = '';
  40. for (let keys in this.frequency) {
  41. if(this.frequency[keys] < smallest) {
  42. smallest = this.frequency[keys]
  43. countKey = keys
  44. }
  45. }
  46. delete this.frequency[countKey];
  47. delete this.capacity[countKey];
  48. }
  49. this.capacity[key] = {key: value}
  50. this.frequency[key] = 0
  51. };
  52.  
  53. /**
  54. * Your LFUCache object will be instantiated and called as such:
  55. * var obj = Object.create(LFUCache).createNew(capacity)
  56. * var param_1 = obj.get(key)
  57. * obj.put(key,value)
  58. */
  59.  
  60. var cache = new LFUCache(2);
  61.  
  62. cache.put(1, 1);
  63. cache.put(2, 2);
  64. console.log(cache.get(1)); // returns 1
  65. cache.put(3, 3); // evicts key 2
  66. console.log(cache.get(2)); // returns -1 (not found)
  67. console.log(cache.get(3)); // returns 3.
  68. cache.put(4, 4); // evicts key 1.
  69. console.log(cache.get(1)); // returns -1 (not found)
  70. console.log(cache.get(3)); // returns 3
  71. console.log(cache.get(4)); // returns 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement