Guest User

Untitled

a guest
Feb 21st, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. /**
  2. * @param {number} capacity
  3. */
  4. var LFUCache = function(capacity) {
  5.  
  6. this.capacity = capacity;
  7. this.count = 0;
  8. this.frequency = {};
  9. this.sorted = [];
  10. };
  11.  
  12. /**
  13. * @param {number} key
  14. * @return {number}
  15. */
  16. LFUCache.prototype.get = function(key) {
  17. if (this[key]) {
  18. this.count ++;
  19. if (!this.frequency[key]) {
  20. this.frequency[key] = {
  21. 'recent': this.count,
  22. 'number': 1
  23. }
  24. } else {
  25. this.frequency[key]['recent'] = this.count;
  26. this.frequency[key]['number'] ++;
  27. }
  28. return this[key];
  29. } else {
  30. return -1
  31. }
  32. };
  33.  
  34. /**
  35. * @param {number} key
  36. * @param {number} value
  37. * @return {void}
  38. */
  39. LFUCache.prototype.put = function(key, value) {
  40. if (this.length < this.capacity) {
  41. this[key] = value;
  42. } else {
  43. for (var key in this.frequency) {
  44. this.sorted.push([key, this.frequency[key]])
  45. }
  46. this.sorted.sort((a,b)=>{
  47. return a[1]['number']-b[1]['number']===0 ? a[1]['recent']-b[1]['recent'] : a[1]['number']-b[1]['number'];
  48. })
  49. if (this.sorted[0]!==undefined) {
  50. let deleteKey = this.sorted[0][0];
  51. delete this.frequency[deleteKey];
  52. delete this[deleteKey];
  53. }
  54. this[key] = value;
  55. console.log(this.sorted)
  56. }
  57. };
Add Comment
Please, Sign In to add comment