How to create a simple, non-secure hash function for JavaScript?

Sometimes, we want to create a simple, non-secure hash function for JavaScript.

In this article, we’ll look at how to create a simple, non-secure hash function for JavaScript.

How to create a simple, non-secure hash function for JavaScript?

To create a simple, non-secure hash function for JavaScript, we can create our own function.

For instance, we write

const hashCode = (str) => {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash = hash & hash;
  }
  return hash;
};

to create the hashCode function that takes the str string and creates a hash.

In it, we loop through the characters in str.

And we update the hash by doing a left shift by 5 bits.

Then we subtract the hash and add the character code of the character at i to it.

And the we convert hash to a 32 bit integer with hash & hash.

Conclusion

To create a simple, non-secure hash function for JavaScript, we can create our own function.