Skip to content

Commit 7873ecb

Browse files
authored
Create Hashing.js
1 parent 0315c8a commit 7873ecb

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Hashes/Hashing.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<script>
2+
// HashTable Implementation
3+
class HashTable {
4+
constructor() {
5+
this.table = new Array(10);
6+
this.size = 0;
7+
}
8+
9+
// private function to convert key to index
10+
// _ shows that the function is private
11+
_setKey(key) {
12+
return key % 10;
13+
}
14+
15+
// insert value in the hashtable
16+
insert(value) {
17+
const index = this._setKey(value);
18+
this.table[index] = value;
19+
this.size++;
20+
}
21+
22+
get(key) {
23+
const target = this._setKey(key);
24+
return this.table[target];
25+
}
26+
27+
search(value) {
28+
const index = this._setKey(value);
29+
if (this.table[index] == value)
30+
console.log("The value is found at index : ", index);
31+
else
32+
console.log("Not found");
33+
}
34+
35+
delete(key) {
36+
const index = this._setKey(key);
37+
38+
if (this.table[index]) {
39+
this.table[index] = [];
40+
this.size--;
41+
return true;
42+
} else {
43+
return false;
44+
}
45+
}
46+
}
47+
48+
const hashExample = new HashTable();
49+
// insert
50+
hashExample.insert(100);
51+
hashExample.insert(87);
52+
hashExample.insert(86);
53+
hashExample.insert(12);
54+
hashExample.insert(9);
55+
56+
57+
console.log(hashExample.table); // -> shows the hash table
58+
59+
// search
60+
hashExample.search(87); // found
61+
hashExample.search(10); // not found
62+
63+
// delete
64+
hashExample.delete(12);
65+
66+
// showing table after deletion
67+
console.log(hashExample.table);
68+
69+
</script>

0 commit comments

Comments
 (0)