I need to convert strings to some form of hash. Is this possible in JavaScript?
I\'m not utilizing a server-side language so I can\'t do it that way.
Adding this because nobody did yet, and this seems to be asked for and implemented a lot with hashes, but it's always done very poorly...
This takes a string input, and a maximum number you want the hash to equal, and produces a unique number based on the string input.
You can use this to produce a unique index into an array of images (If you want to return a specific avatar for a user, chosen at random, but also chosen based on their name, so it will always be assigned to someone with that name).
You can also use this, of course, to return an index into an array of colors, like for generating unique avatar background colors based on someone's name.
function hashInt (str, max = 1000) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash = hash & hash;
}
return Math.round(max * Math.abs(hash) / 2147483648);
}