forked from hacktoberfest17/programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashtable_in_Js.js
More file actions
75 lines (66 loc) · 1.93 KB
/
Hashtable_in_Js.js
File metadata and controls
75 lines (66 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//Hashtable implementation in Javascript
var hash = (string,max)=>{
var hash = 0;
for(let i = 0;i<string.length;i++){
hash += string.charCodeAt(i);
}
return hash%max;
}
const HashTable = function(){
this.storage = [];
this.storageLimit = 4;
this.print = ()=>{
console.log(this.storage);
}
this.add = (key,value)=>{
const index = hash(key,this.storageLimit);
if(this.storage[index] === undefined){
this.storage[index] = [[key,value]];
}else{
var inserted = false;
for(let i = 0;i<this.storage[index].length;i++){
if(this.storage[index][i][0] === key){
this.storage[index][i][1] = value;
inserted = true;
}
if(inserted === false){
this.storage[index].push([key,value]);
}
}
}
}
this.lookUp = (key)=>{
const index = hash(key,this.storageLimit);
if(this.storage[index] === undefined){
return "Not found";
}else{
for(let i = 0;i<this.storage[index].length;i++){
if(this.storage[index][i][0] === key){
return this.storage[index][i];
}else{
return "Not entry found";
}
}
}
}
this.remove = (key)=>{
const index = hash(key,this.storageLimit);
if(this.storage[index] === undefined){
return false;
}else{
for(let i = 0;i<this.storage[index].length;i++){
if(this.storage[index][i][0] === key){
delete this.storage[index][i];
}
}
}
}
}
var setH = new HashTable();
setH.add('sam','js');
setH.add('ben','java');
setH.add('123','php');
setH.add('abra','Dexter');
setH.remove('sam');
console.log(setH.lookUp('am'));
setH.print();