Advertisement
rgruber

Javascript KVStore Class [TTL]

Dec 25th, 2022 (edited)
1,005
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class KVStore {
  2.   constructor() {
  3.     this.store = {};
  4.     this.timer = setInterval(this.cleanup.bind(this), 1000);
  5.   }
  6.  
  7.   set(key, value, ttl) {
  8.     this.store[key] = { value: value, ttl: ttl, expiration: Date.now() + ttl };
  9.   }
  10.  
  11.   get(key) {
  12.     var entry = this.store[key];
  13.     if (entry && entry.expiration > Date.now()) {
  14.       return entry.value;
  15.     }
  16.     return undefined;
  17.   }
  18.  
  19.   delete(key) {
  20.     delete this.store[key];
  21.   }
  22.  
  23.   cleanup() {
  24.     var now = Date.now();
  25.     for (var key in this.store) {
  26.       if (this.store[key].expiration <= now) {
  27.         delete this.store[key];
  28.       }
  29.     }
  30.   }
  31. }
  32.  
  33. var store = new KVStore();
  34.  
  35. store.set('foo', 'bar', 1000);
  36. console.log(store.get('foo')); // 'bar'
  37.  
  38. setTimeout(function() {
  39.   console.log(store.get('foo')); // undefined
  40. }, 1100);
  41.  
Tags: KVStore
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement