Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. class Cache {
  2. // valid_for: <Integer>; number of minutes until marked stale and removed.
  3. // cleanup_after: <Integer>; number of additions between cleanup process.
  4. constructor ({ valid_for, cleanup_after }) {
  5. this.valid_for = valid_for;
  6. this.cleanup_after = cleanup_after;
  7. this.cleanup_in_process = false;
  8.  
  9. this.cleanup_idx = 0;
  10. this.map = {
  11.  
  12. };
  13. }
  14.  
  15. cleanup () {
  16. this.cleanup_in_process = true;
  17. // this guarantees that the previous thread and return will not be blocked by
  18. // this process.
  19. setTimeout(() => {
  20. Object.keys(this.map).forEach(o => {
  21. if (this.map[o].expires < +new Date()) delete this.map[o];
  22. });
  23.  
  24. this.cleanup_in_process = false;
  25. this.cleanup_idx = 0;
  26. });
  27. }
  28.  
  29. setItem (key, value) {
  30. // increment the index of insertions since cleanup.
  31. this.cleanup_idx++;
  32. this.map[key] = {
  33. value,
  34. expires: +new Date() + (1000 * 60 * this.valid_for),
  35. };
  36.  
  37. // check if it is time to clean up (x number of arbitrary submissions).
  38. if (this.cleanup_idx === this.cleanup_after) {
  39. // run async at next thread availability.
  40. this.cleanup();
  41. }
  42.  
  43. return this.map[key].value;
  44. }
  45.  
  46. getItem (key) {
  47. return this.map[key].value;
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement