Last active
January 10, 2022 16:51
-
-
Save miketromba/46fe738d9e536a92ffdfa352ecf19bd8 to your computer and use it in GitHub Desktop.
ItemCache.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Very simple item cache (easily add .flush/dump and/or .delete functions if needed) | |
class ItemCache { | |
constructor({ get, init }){ | |
this._items = {} | |
this.getItem = get | |
// use init to initialize the cache: init(set){ getItems, then set(key, | |
// item) for each } | |
this._init = init | |
this._initialized = false | |
} | |
get items(){ | |
return Object.values(this._items) | |
} | |
async init(context){ // context is optional | |
if(this._initialized){ | |
throw new Error('Cannot initialize ItemCache more than once.') | |
} | |
if(this._init){ | |
await this._init(this.set.bind(this), context) | |
} | |
this._initialized = true | |
} | |
async get(key){ | |
if(!this._items[key]){ | |
this.set(key, await this.getItem(key)) | |
} | |
return this._items[key] | |
} | |
set(key, item){ | |
this._items[key] = item | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment