Created
May 18, 2018 20:23
-
-
Save mikesparr/1e7e114658cca27292c929ff68c3d961 to your computer and use it in GitHub Desktop.
Function to create unsigned int hash of a string in pure JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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