Guest User

Untitled

a guest
Feb 21st, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. class LFUCache {
  2. constructor(capacity) {
  3. this.capacity = capacity;
  4. this.cache = {};
  5. this.lfu = null;
  6. }
  7. get(key) {
  8. if (Object.keys(this.cache).contains(key)) {
  9. let { value } = this.cache[key];
  10. this.cache[key].frequency += 1;
  11. this.cache[key].last = new Date();
  12. return value;
  13. }
  14. return -1;
  15. }
  16.  
  17. put(key, value) {
  18. let keys = Object.keys(this.cache);
  19. if (!keys.contains(key)) {
  20. if (keys.length === this.capacity) {
  21. for (let k = 0; k < keys.length; k += 1) {
  22. if (this.lfu) {
  23. if (this.cache[k].frequency < this.cache[this.lfu].frequency) {
  24. this.lfu = k;
  25. } else if (this.cache[k].frequency === this.cache[this.lfu].frequency) {
  26. if (this.cache[k].last < this.cache[this.lfu].last) {
  27. this.lfu = k;
  28. }
  29. }
  30. } else {
  31. this.lfu = k;
  32. }
  33. }
  34. delete this.cache[this.lfu];
  35. this.lfu = null;
  36. }
  37. this.cache[key] = {
  38. value,
  39. frequency: 0,
  40. last: new Date(),
  41. };
  42. }
  43. }
  44. }
Add Comment
Please, Sign In to add comment