← 中文资源

简体中文版本

倒排索引 Map+Set 多重映射

每个标签映射到一个 id 集合:新增、删除顺手清空空桶,跨标签并集用 Set 去重一次收集。倒排索引让按标签检索始终是常数级查找。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

倒排索引 Map+Set 多重映射可以归结为类 TagIndex。 for (const tag of tags) 与 for (const id of this.index.get(tag) ?? []) 嵌套——内层在外层的每一步各跑一遍。 顶层就这几处状态:catalog。 返回值是全新构造的——入参不会被交回去。

使用要点

  • 每一步打印都带着自己的标签:audio:、audio or video:、audio after remove:。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。 状态都挂在模块顶层:catalog。

核心语句

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

代码示例

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'));