Skip to content

Instantly share code, notes, and snippets.

@amplicity
Created August 11, 2020 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amplicity/20a7815e35818d5ebc043b624eb33506 to your computer and use it in GitHub Desktop.
Save amplicity/20a7815e35818d5ebc043b624eb33506 to your computer and use it in GitHub Desktop.
class Store{
constructor(){
this.store = new Map();
}
put(key, value, ttl){
ttl = Date.now() + ttl;
this.store.set(key, {value,ttl});
this._cleanOldKeys();
}
get(key){
const item = this.store.get(key);
if (!item){
return 'No key exists.';
}
if (Date.now() > item.ttl){
this.store.delete(key);
return 'Key has expired and has been removed.';
}
return item.value;
}
_cleanOldKeys(){
const timestamp = Date.now();
for (let [key, data] of this.store){
if (timestamp > data.ttl){
this.store.delete(key);
}
}
}
}
const myStore = new Store();
myStore.put('hello', 'goodbye', 4);
myStore.put('hello1', 'goodbye1', 4);
myStore.put('hello2', 'goodbye2', 4);
myStore.put('hello3', 'goodbye3', 4);
myStore.put('hello3', 'goodbye3', 4);
setTimeout(()=> {
myStore.put('hello3', 'goodbye3', 4);
console.log('Attempt to get hello key: ',myStore.get('hello'));
console.log('Attempt to get key that never existed: ',myStore.get('blank-key'));
console.log('Date.now', Date.now());
console.log('myStore: ',myStore.store);
}, 50);
@amplicity
Copy link
Author

To run:

node for-ray.js

Sample output:

Attempt to get hello key:  No key exists.
Attempt to get key that never existed:  No key exists.
Date.now 1597172027562
myStore:  Map { 'hello3' => { value: 'goodbye3', ttl: 1597172027565 } }

@amplicity
Copy link
Author

Switched over to Map data type from Object because:

  • Maps can retrieve size from size property
  • Maps have no default keys, no chance of key collision.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment