Skip to content

Instantly share code, notes, and snippets.

@Israel025
Last active April 10, 2019 19:48
Show Gist options
  • Save Israel025/08f43679ac2c7c4136bce162baeea455 to your computer and use it in GitHub Desktop.
Save Israel025/08f43679ac2c7c4136bce162baeea455 to your computer and use it in GitHub Desktop.
Implentation of a hash table
function HashTable() {
this.table = new Array();
this.dupList = [];
}
HashTable.prototype.hashMethod = function(input){
let strInput = input.toString();
const encoder = 27;
let hashCode = 0;
for (let i = 0; i < strInput.length; i++) {
hashCode += encoder * hashCode + strInput.charCodeAt(i);
}
hashCode = hashCode % 150;
if (hashCode < 0) {
hashCode += 151;
}
return parseInt(hashCode);
}
HashTable.prototype.getKey = function(value){
return (`Key for ${value} --> ${HashTable.hashMethod(value)}`);
}
HashTable.prototype.storeData = function(data) {
let index = this.hashMethod(data);
if (this.table[index] === undefined){
this.table[index] = [data];
}
else if (this.table[index] !== undefined){
this.table[index].push(data);
if (!this.dupList.includes(index)){
this.dupList.push([index, data]);
}
}
}
HashTable.prototype.getAllItems = function() {
for (var i = 0; i < this.table.length; i++) {
if (this.table[i] != undefined){
console.log(`Index ${i} contains ${this.table[i]}`);
}
}
}
HashTable.prototype.getDuplicates = function(array) {
for(let i = 0; i<array.length; i++){
this.storeData(array[i]);
}
this.dupList.map((pairs) =>{
return (`${pairs[1]} occurs ${this.table[pairs[0]].length}`)
})
}
let arry = [3,5,5,3,3,"g","rt"]
let calc = new HashTable();
console.log (calc.getDuplicates(arry));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment