Skip to content

Instantly share code, notes, and snippets.

@selmanj
Created June 8, 2019 05:59
Show Gist options
  • Save selmanj/4975670e31f36e9e5dee8cc078e23b06 to your computer and use it in GitHub Desktop.
Save selmanj/4975670e31f36e9e5dee8cc078e23b06 to your computer and use it in GitHub Desktop.
export class Table<T> {
private lastId = -1;
private readonly data: Map<number, T> = new Map();
private readonly indexes: Map<keyof T, Map<T[keyof T], number[]>> = new Map();
constructor(...indexes: Array<keyof T>) {
for (const idx of indexes) {
this.indexes.set(idx, new Map());
}
}
insert(obj: T): number {
this.data.set(++this.lastId, obj);
for (const [idx, valMap] of this.indexes.entries()) {
const val = obj[idx];
const ids = valMap.get(val);
if (ids === undefined) {
valMap.set(val, [this.lastId]);
} else {
ids.push(this.lastId);
}
}
return this.lastId;
}
get(id: number): T | undefined {
return this.data.get(id);
}
getByIndex<K extends keyof T>(idx: K, val: T[K]): T[] {
const valMap = this.indexes.get(idx);
if (valMap === undefined) {
throw new Error(`No such index: ${idx}`);
}
const ids = valMap.get(val);
if (ids === undefined) {
return [];
}
return ids.map((id) => {
const v = this.get(id);
if (v === undefined) {
throw new Error(`Runtime error while looking up index ${idx},` +
` had a mapping for object ${id} but none found`);
}
return v;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment