Skip to content

Instantly share code, notes, and snippets.

@bit-app-3000
Forked from jlevy/simple-hash.js
Created December 11, 2024 13:16
Show Gist options
  • Select an option

  • Save bit-app-3000/d0fbe67b05f8c7e8e588d2349ab4de27 to your computer and use it in GitHub Desktop.

Select an option

Save bit-app-3000/d0fbe67b05f8c7e8e588d2349ab4de27 to your computer and use it in GitHub Desktop.
Fast and simple insecure string hash for JavaScript
// This is a simple, *insecure* 32-bit hash that's short, fast, and has no dependencies.
// For algorithmic use cases, such as bucketing in hashtables, where security isn't needed
// and 32 bits is enough (that is, rare collisions are acceptable).
// 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);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment