Skip to content

Instantly share code, notes, and snippets.

@cron13
Created October 18, 2019 09:32
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 cron13/b8a0419ecf037a81f93b78f7783a4c22 to your computer and use it in GitHub Desktop.
Save cron13/b8a0419ecf037a81f93b78f7783a4c22 to your computer and use it in GitHub Desktop.
numeric hash from string. BKDRHash
var BKDRHash = function(str) {
var seed = 131;
var seed2 = 137;
var hash = 0;
// make hash more sensitive for short string like 'a', 'b', 'c'
str += 'x';
// Note: Number.MAX_SAFE_INTEGER equals 9007199254740991
var MAX_SAFE_INTEGER = parseInt(9007199254740991 / seed2);
for(var i = 0; i < str.length; i++) {
if(hash > MAX_SAFE_INTEGER) {
hash = parseInt(hash / seed2);
}
hash = hash * seed + str.charCodeAt(i);
}
return hash;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment