Skip to content

Commit 1196b58

Browse files
feat: implement hash table data structure class
1 parent 4c53a79 commit 1196b58

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/hash-table/HashTable.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
export class HashTable {
2+
protected size: number;
3+
private data;
4+
5+
constructor(size: number) {
6+
this.size = size;
7+
this.data = new Array(size);
8+
}
9+
10+
private hash(key: string) {
11+
let hash = 0;
12+
for (let i = 0; i < key.length; i++) {
13+
hash = (hash + key.charCodeAt(i) * i) % this.data.length;
14+
}
15+
return hash;
16+
}
17+
18+
public set(key: string, value: any) {
19+
let address = this.hash(key);
20+
if (!this.data[address]) {
21+
this.data[address] = [];
22+
}
23+
this.data[address].push([key, value]);
24+
return this.data;
25+
}
26+
27+
public get(key: string) {
28+
let address = this.hash(key);
29+
const currentBucket = this.data[address];
30+
if (currentBucket) {
31+
for (let i = 0; i < currentBucket.length; i++) {
32+
if (currentBucket[i][0] === key) {
33+
return currentBucket[i][1];
34+
}
35+
}
36+
}
37+
return undefined;
38+
}
39+
40+
public keys() {
41+
const keysArray = [];
42+
for (let i = 0; i < this.data.length; i++) {
43+
if (this.data[i]) {
44+
keysArray.push(this.data[i][0][0]);
45+
}
46+
}
47+
return keysArray;
48+
}
49+
}

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
console.log('Typescript Data Structures & Algorithms');
22
import './arrays/arrayClass';
3+
import './hash-table/HashTable';

0 commit comments

Comments
 (0)