Javascript Data Structure HashTable

Description

Javascript Data Structure HashTable

function HashTable() {
  this.table = new Array(137);/*  www .j a v  a  2s .  c  om*/
  this.simpleHash = simpleHash;
  this.betterHash = betterHash;
  this.showDistro = showDistro;
  this.put = put;
  // this.get = get;
}

function put(data) {
  let pos = this.betterHash(data);
  this.table[pos] = data;
}

function simpleHash(data) {
  let total = 0;
  for (let i = 0; i < data.length; ++i) {
    total += data.charCodeAt(i);
  }
  console.log("Hash value: " + data + " -> " + total);
  return total % this.table.length;
}

function showDistro() {
  let n = 0;
  for (let i = 0; i < this.table.length; ++i) {
    if (this.table[i] != undefined) {
      console.log(i + ": " + this.table[i]);
    }
  }
}

function betterHash(string) {
  const H = 37;
  let total = 0;
  for (let i = 0; i < string.length; ++i) {
    total += H * total + string.charCodeAt(i);
  }
  total = total % this.table.length;
  if (total < 0) {
    total += this.table.length - 1;
  }
  return parseInt(total);
}

let someNames = [ "David", "Jennifer", "Donnie", "Raymond", "Cynthia", "Mike",
    "Clayton", "Danny", "Jonathan" ];
let hTable = new HashTable();
for (let i = 0; i < someNames.length; ++i) {
  hTable.put(someNames[i]);
}
hTable.showDistro();



PreviousNext

Related