Skip to content

Instantly share code, notes, and snippets.

@wubin1989
Forked from jedp/gist:3166329
Created June 30, 2023 15:00
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 wubin1989/673f4f6b4456b9841ec44f5cd9158c46 to your computer and use it in GitHub Desktop.
Save wubin1989/673f4f6b4456b9841ec44f5cd9158c46 to your computer and use it in GitHub Desktop.
Hash to small integer
// Hash 'string' to a small number (digits default: 6)
function hash(string, digits) {
digits = digits || 6;
var m = Math.pow(10, digits+1) - 1;
var phi = Math.pow(10, digits) / 2 - 1;
var n = 0;
for (var i = 0; i < string.length; i++) {
n = (n + phi * string.charCodeAt(i)) % m;
}
return n.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment