Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Cache {
- // valid_for: <Integer>; number of minutes until marked stale and removed.
- // cleanup_after: <Integer>; number of additions between cleanup process.
- constructor ({ valid_for, cleanup_after }) {
- this.valid_for = valid_for;
- this.cleanup_after = cleanup_after;
- this.cleanup_in_process = false;
- this.cleanup_idx = 0;
- this.map = {
- };
- }
- cleanup () {
- this.cleanup_in_process = true;
- // this guarantees that the previous thread and return will not be blocked by
- // this process.
- setTimeout(() => {
- Object.keys(this.map).forEach(o => {
- if (this.map[o].expires < +new Date()) delete this.map[o];
- });
- this.cleanup_in_process = false;
- this.cleanup_idx = 0;
- });
- }
- setItem (key, value) {
- // increment the index of insertions since cleanup.
- this.cleanup_idx++;
- this.map[key] = {
- value,
- expires: +new Date() + (1000 * 60 * this.valid_for),
- };
- // check if it is time to clean up (x number of arbitrary submissions).
- if (this.cleanup_idx === this.cleanup_after) {
- // run async at next thread availability.
- this.cleanup();
- }
- return this.map[key].value;
- }
- getItem (key) {
- return this.map[key].value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement