Guest User

Untitled

a guest
Nov 19th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. /**
  2. * A cache that stores values for a specifed period of time.
  3. * TTL = time to live, FYI
  4. * FYI = for your information, LOL
  5. * LOL = laughing out loud
  6. * ME = ridiculous
  7. */
  8. class TtlCache {
  9. constructor() {
  10. this.hash = {};
  11. }
  12.  
  13. /**
  14. * @param key {string|number|function|object|null|undefined} the key to hash on
  15. * @param value the value to store for the given key
  16. * @param ttl the time to live. how long to keep in the cache. if nothing is passed in, then it will never expire
  17. * */
  18. set(key, value, ttl=Number.POSITIVE_INFINITY) {
  19. this.hash[key] = {
  20. end : Date.now() + ttl,
  21. value : value
  22. };
  23. }
  24.  
  25. /**
  26. * @return the value for the given key. undefined if its not in the Ttlcache
  27. * */
  28. get(key) {
  29. let hashItem = this.hash[key];
  30.  
  31. if (hashItem) {
  32. if (Date.now() <= hashItem.end) {
  33. return hashItem.value;
  34. } else {
  35. delete this.hash[key]; // cleanup
  36. }
  37. }
  38.  
  39. return undefined;
  40. }
  41. }
  42.  
  43. module.exports = TtlCache;
Add Comment
Please, Sign In to add comment