UNPKG

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

66 lines (57 loc) 1.85 kB
/** * A key-value store that persists data using local storage. */ export default class LocalStoreContext { private context: Map<string, string | number | boolean> = new Map() private contextNamespace: string constructor(contextName: string) { 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. */ public set(key: string, value: string | number | boolean, valueType: 'string'|'number'|'boolean'): void { this.context[key] = `${valueType}:${value}` this.persistContext() } public get(key: string): string | number | boolean { 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}`) } } public remove(key: string): void { delete this.context[key] this.persistContext() } public length(): number { return Object.keys(this.context).length } public clear(): void { this.context = new Map() this.persistContext() } private rehydrateContext(): void { const lsCtx = window.localStorage.getItem(this.contextNamespace) || '{}' this.context = JSON.parse(lsCtx) } private persistContext(): void { window.localStorage.setItem(this.contextNamespace, JSON.stringify(this.context)) } }