agentscape
Version:
Agentscape is a library for creating agent-based simulations. It provides a simple API for defining agents and their behavior, and for defining the environment in which the agents interact. Agentscape is designed to be flexible and extensible, allowing
57 lines • 1.66 kB
JavaScript
/**
* A key-value store that persists data using local storage.
*/
export default class LocalStoreContext {
constructor(contextName) {
this.context = new Map();
this.contextNamespace = contextName;
this.rehydrateContext();
}
/**
* Set a value in local storage.
* @param key The key to store the value under.
* @param value The value to store.
*/
set(key, value, valueType) {
this.context[key] = `${valueType}:${value}`;
this.persistContext();
}
get(key) {
const pair = this.context[key];
if (!pair) {
console.warn(`Key ${key} not found in local storage`);
this.clear();
// location.reload()
}
const [type, value] = pair.split(':');
switch (type) {
case 'string':
return value;
case 'number':
return parseFloat(value);
case 'boolean':
return value === 'true';
default:
throw new Error(`Unknown type ${type}`);
}
}
remove(key) {
delete this.context[key];
this.persistContext();
}
length() {
return Object.keys(this.context).length;
}
clear() {
this.context = new Map();
this.persistContext();
}
rehydrateContext() {
const lsCtx = window.localStorage.getItem(this.contextNamespace) || '{}';
this.context = JSON.parse(lsCtx);
}
persistContext() {
window.localStorage.setItem(this.contextNamespace, JSON.stringify(this.context));
}
}
//# sourceMappingURL=LocalStoreContext.js.map