Mike Mike - 3 days ago 5
Javascript Question

Make choice from array semi-randomly based on string

I have this problem. I'd like to make random a choice from array

[1,2,3,4]
based on arbitrary 6 letter string in such way that this choice is always same if string is same.

So if i have string 'dogdog' function would return always
'3'
for example, but
'4'
for 'bigcat' etc.

I think the solution might be first hashing the string. How could one convert hash string into choice from array?

Answer

You can calculate a hash from a string and take the array item at [hash % array.length]. An example with the DJB hashfunc (see http://www.cse.yorku.ca/~oz/hash.html for more):

function djbHash(s) {
    let hash = 5381;

    for (let c of s) {
        hash = hash * 33 + c.charCodeAt(0);
    }
    return hash;
}

function mapToValues(s, values) {
    return values[djbHash(s) % values.length];
}

console.log(mapToValues('dogdog', [1, 2, 3, 4]));
console.log(mapToValues('bigcat', [1, 2, 3, 4]));

Comments