1class HashTable {
2 constructor(capacity = 5) {
3 this.buckets = new Array(capacity).fill(null).map(() => []);
4 this.capacity = capacity;
5 }
6
7 hash(key) {
8 return ((key % this.capacity) + this.capacity) % this.capacity;
9 }
10
11 put(key) {
12 const idx = this.hash(key);
13 if (this.buckets[idx].includes(key)) return; // 已存在
14 this.buckets[idx].push(key);
15 }
16
17 get(key) {
18 const idx = this.hash(key);
19 return this.buckets[idx].includes(key) ? key : null;
20 }
21}