Skip to content

Instantly share code, notes, and snippets.

@mikesparr
Created May 18, 2018 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikesparr/1e7e114658cca27292c929ff68c3d961 to your computer and use it in GitHub Desktop.
Save mikesparr/1e7e114658cca27292c929ff68c3d961 to your computer and use it in GitHub Desktop.
Function to create unsigned int hash of a string in pure JS
const hash = (str) => {
let val = 0;
const strlen = str.length;
if (strlen === 0) { return val; }
for (let i = 0; i < strlen; ++i) {
const code = str.charCodeAt(i);
val = ((val << 5) - val) + code;
val &= val; // Int32
}
return (val >>> 0); // uInt32
};
// usage
const myHash = hash("Hello, world"); // 3818678700
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment