Generate deterministic hash number between 0 and 1 from string

Viewed 1124

I'm looking for a way to 'hash' strings in JavaScript, so that

  • the result is deterministic (aways yields same result with the same input string)
  • the result is a decimal number between 0 and 1
  • the results are (kind of) uniformly spread out in the 0 to 1 space.

For example:

decimalHash('hallo world') = 0.145     // some made up number
decimalHash('how are you?') = 0.345    // some made up number
decimalHash('fine, thanks!') = 0.945   // some made up number

I've searched for such a method, but all the hash functions I found so far have different characteristics. Any help would be appreciated!

1 Answers

You could built an own by using a value for each chatacter with a factor and sum this value. At the end take only fractional part.

This approach may produce collisions.

const decimalHash = string => {
    let sum = 0;
    for (let i = 0; i < string.length; i++)
        sum += (i + 1) * string.codePointAt(i) / (1 << 8)
    return sum % 1;
}

console.log(decimalHash('a'));
console.log(decimalHash('aa'));
console.log(decimalHash('hallo world'));
console.log(decimalHash('how are you?'));
console.log(decimalHash('fine, thanks!'));

Related