返回

深入剖析 TypeScript 中的字典数据结构

前端

TypeScript 数据结构与算法:字典

字典是一种数据结构,它允许你使用键值对来存储数据。字典的优点是它可以快速查找数据,时间复杂度为 O(1)。

实现字典

export class Dictionary<K, V> {
  private data: Record<K, V> = {};

  set(key: K, value: V): void {
    this.data[key] = value;
  }

  get(key: K): V | undefined {
    return this.data[key];
  }

  has(key: K): boolean {
    return this.data.hasOwnProperty(key);
  }

  delete(key: K): void {
    delete this.data[key];
  }

  keys(): Iterable<K> {
    return Object.keys(this.data);
  }

  values(): Iterable<V> {
    return Object.values(this.data);
  }

  entries(): Iterable<[K, V]> {
    return Object.entries(this.data);
  }

  forEach(callback: (value: V, key: K) => void): void {
    Object.entries(this.data).forEach(([key, value]) => callback(value, key));
  }
}

用例

const dictionary = new Dictionary<string, number>();

dictionary.set("Apple", 1);
dictionary.set("Banana", 2);
dictionary.set("Cherry", 3);

console.log(dictionary.get("Apple")); // 1
console.log(dictionary.has("Banana")); // true
dictionary.delete("Cherry");
console.log(dictionary.keys()); // ["Apple", "Banana"]

总结

字典是一种在 TypeScript 中存储键值对的强大数据结构。它提供了一系列方法,包括设置、获取、删除和遍历键值对。字典对于需要快速查找数据的应用程序非常有用。