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