import { create, has } from '../../../core/object'; import { MetaContext, MetaObject, $NAME } from '../MetaContext'; export const $ID = '$id'; export type HashString = { hashString(str: string, seed?: number): number }; export const withId = MetaContext & HashString>(MetaContextBase: TMetaContextBase) => class extends MetaContextBase { protected _ids = create(); getId(id: number) { return this._ids[id]; } resolveId(id: number) { if (!has(this._ids, id)) throw new TypeError(`MetaContext.resolveId(): ${id} is not found`); return this._ids[id]; } protected createMetaObject(props: any) { const ret = super.createMetaObject(props); if (!has(ret, $ID)) ret[$ID] = this.hashString(ret[$NAME]); const id = ret[$ID]; if (has(this._ids, id)) throw new TypeError(`MetaContext.register(): id ${id} is already in use for ${this.resolveId(id)[$NAME]}`); this._ids[id] = ret; return ret; } };