Skip to content

Instantly share code, notes, and snippets.

@aculich
Forked from jlevy/simple-hash.js
Created May 15, 2022 20:38
Show Gist options
  • Save aculich/2dabf4c1368fb5a5a30095be81c8863d to your computer and use it in GitHub Desktop.
Save aculich/2dabf4c1368fb5a5a30095be81c8863d to your computer and use it in GitHub Desktop.
Fast and simple insecure string hash for JavaScript
// This is a simple, *insecure* hash that's short, fast, and has no dependencies.
// For algorithmic use, where security isn't needed, it's way simpler than sha1 (and all its deps)
// or similar, and with a short, clean (base 36 alphanumeric) result.
// Loosely based on the Java version; see
// https://stackoverflow.com/questions/6122571/simple-non-secure-hash-function-for-javascript
const simpleHash = str => {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash &= hash; // Convert to 32bit integer
}
return new Uint32Array([hash])[0].toString(36);
};
@romgrk
Copy link

romgrk commented Aug 25, 2024

For anyone landing here from google, I plotted this hashing function distribution using this stackoverflow answer's methodology, below are the results. I've also been benchmarking the performance, murmur2 has the best performance in JS, so use that function if you need one.

Simple hash:
simple

Murmur2:
murmur2_improved

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment