tokenとIDを双方向変換しつつストレージに保存するクラス
2021/6/21 20:02:00
class Token_store {
constructor() {
this.store = localforage.createInstance({ name: 'Tokens' });
this.token_array = [];
this.id_by_token = new Map();
}
token_get_by_id(id) {
return this.token_array[id];
}
id_get_by_token(token) {
let id = this.id_by_token.get(token);
if (id?.constructor != Number) {
this.add_token(token);
id = this.id_by_token.get(token);
}
console.assert(id?.constructor == Number);
return id;
}
add_token(token) {
const id = this.token_array.length;
this.token_array[id] = token;
this.id_by_token.set(token, id);
this.save_async_with_delay();
}
async load_async() {
this.token_array = await this.store.getItem('token_array');
for (let i = 0; i < this.token_array.length; i++) {
this.id_by_token.set(token, i);
}
}
async save_async() {
this.store.setItem('token_array', this.token_array);
}
async save_async_with_delay() {
if (this.saving) {
return;
}
await this.save_async();
setTimeout(() => {
this.saving = false;
}, SAVE_DELAY);
}
}