Creating better hash functions

The lose-lose hash function we implemented is not a good hash function, as we have concluded (too many collisions). We would have multiple collisions if we used this function. A good hash function is composed of certain factors: the time to insert and retrieve an element (performance) and also a low probability of collisions. We can find several different implementations on the internet, or we can create our own.

Another simple hash function that we can implement and which is better than the lose-lose hash function is djb2, which is as follows:

djb2HashCode(key) {  const tableKey = this.toStrFn(key); // {1}  let hash = 5381; // {2}  for (let i = 0; i < tableKey.length; i++) { // {3} hash = (hash * 33) + tableKey.charCodeAt(i); ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.