Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class KVStore {
- constructor() {
- this.store = {};
- this.timer = setInterval(this.cleanup.bind(this), 1000);
- }
- set(key, value, ttl) {
- this.store[key] = { value: value, ttl: ttl, expiration: Date.now() + ttl };
- }
- get(key) {
- var entry = this.store[key];
- if (entry && entry.expiration > Date.now()) {
- return entry.value;
- }
- return undefined;
- }
- delete(key) {
- delete this.store[key];
- }
- cleanup() {
- var now = Date.now();
- for (var key in this.store) {
- if (this.store[key].expiration <= now) {
- delete this.store[key];
- }
- }
- }
- }
- var store = new KVStore();
- store.set('foo', 'bar', 1000);
- console.log(store.get('foo')); // 'bar'
- setTimeout(function() {
- console.log(store.get('foo')); // undefined
- }, 1100);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement