Inverted Index With Map And Set Multimap

Map each tag to a Set of ids in an inverted index, so tag lookups, unions across tags, and removals that prune empty buckets all stay cheap.

TypescriptData Integrity

Code

typescriptsnippet
48 lines
class TagIndex {
  private index = new Map<string, Set<number>>();

  add(id: number, tags: string[]): void {
    for (const tag of tags) {
      let ids = this.index.get(tag);
      if (!ids) {
        ids = new Set();
        this.index.set(tag, ids);
      }
      ids.add(id);
    }
  }

  remove(id: number, tags: string[]): void {
    for (const tag of tags) {
      this.index.get(tag)?.delete(id);
      if (this.index.get(tag)?.size === 0) {
        this.index.delete(tag); // prune empty buckets
      }
    }
  }

  idsFor(tag: string): number[] {
    return [...(this.index.get(tag) ?? [])];
  }

  idsForAny(tags: string[]): number[] {
    const hits = new Set<number>();
    for (const tag of tags) {
      for (const id of this.index.get(tag) ?? []) {
        hits.add(id);
      }
    }
    return [...hits];
  }
}

const catalog = new TagIndex();
catalog.add(1, ['audio', 'new']);
catalog.add(2, ['video', 'new']);
catalog.add(3, ['audio']);

console.log('audio:', catalog.idsFor('audio'));
console.log('audio or video:', catalog.idsForAny(['audio', 'video']).sort((a, b) => a - b));

catalog.remove(3, ['audio']);
console.log('audio after remove:', catalog.idsFor('audio'));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

audio: [ 1, 3 ]
audio or video: [ 1, 2, 3 ]
audio after remove: [ 1 ]

Inside the snippet

One way to read it: the class TagIndex, doing all the work.

The core work runs in nested loops — outer for (const tag of tags), inner for (const id of this.index.get(tag) ?? []).

Top-level bindings catalog hold the demo state — nothing sits inside a function scope.

The return value is newly constructed — inputs are never handed back.

Using it

The run prints audio:, audio or video:, audio after remove: — each prefix names the step that produced it.

Key statements

return [...(this.index.get(tag) ?? [])];
private index = new Map<string, Set<number>>();
for (const id of this.index.get(tag) ?? []) {
  hits.add(id);
}

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `catalog`.