从字符串生成 0 到 1 之间的确定性哈希值

Generate deterministic hash number between 0 and 1 from string

我正在寻找 JavaScript 中 'hash' 字符串的方法,以便

例如:

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

我已经搜索过这样的方法,但是到目前为止我找到的所有哈希函数都具有不同的特征。如有任何帮助,我们将不胜感激!

您可以通过为每个字符使用一个值和一个因子来构建自己的值,然后对这个值求和。最后只取小数部分。

这种方法可能会产生冲突。

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!'));