🤯new hash function method to avoid collisions!

nurbekmalikov

Nurbek Malikov

Posted on October 21, 2024

🤯new hash function method to avoid collisions!

class Hashing {
constructor() {
this.table = new Array(127);
this.size = 0;
}

// indexing every item
_hash(key) {
let position = 0;
for (let i = 0; i < key.length; i++) {
position += key.charCodeAt(i);
}
return position % this.table.length;
}

// put item to the table
set(key, value) {
let index = this._hash(key);

// if key equal to old item's key and values also equal or push it behind
if (this.table[index]) {
  for (let i = 0; i < this.table[index].length; i++) {
    if (this.table[index][i][0] === key) {
      this.table[index][i][1] = value;
      return;
    }
  }
  this.table[index].push([key, value]);
} else {
  this.table[index] = [];
  this.table[index].push([key, value]);
}
this.size++;
Enter fullscreen mode Exit fullscreen mode

}

get(key) {
const target = this._hash(key);

if (this.table[target]) {
  for (let i = 0; i < this.table.length; i++) {
    if (this.table[target][i][0] === key) {
      return this.table[target][i][1];
    }
  }
}
return undefined;
Enter fullscreen mode Exit fullscreen mode

}

remove(key) {
let index = this._hash(key);
if (this.table[index] && this.table[index].length) {
for (let i = 0; i < this.table.length; i++) {
if (this.table[index][i][0] === key) {
this.table[index].splice(i, 1);
this.size--;
return true;
}
}
}
return false;
}

display() {
this.table.forEach((values, index) => {
const chainded = values.map(([key, value]) => [${key}: ${value}]);
console.log(${index} : ${chainded});
});
}
}

💖 💪 🙅 🚩
nurbekmalikov
Nurbek Malikov

Posted on October 21, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related