@idooel/runtime-context
Version:
Runtime data pool with namespaces, stackable contexts, subscriptions and optional persistence. Vue adapter included.
31 lines (25 loc) • 807 B
text/typescript
import type { ContextInitShape, Namespace, DataKey } from './types'
export class Context {
readonly id: string
readonly store: Map<Namespace, Map<DataKey, unknown>>
constructor(init?: ContextInitShape) {
this.id = generateId()
this.store = new Map()
if (init) {
for (const ns of Object.keys(init)) {
const nsMap = new Map<DataKey, unknown>()
const obj = init[ns]
if (obj && typeof obj === 'object') {
for (const key of Object.keys(obj)) {
nsMap.set(key, (obj as any)[key])
}
}
this.store.set(ns, nsMap)
}
}
}
}
function generateId(): string {
// simple unique-ish id sufficient for context identification
return `ctx_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`
}