mattbierner / hamt

Javascript Hash Array Mapped Trie
MIT License
251 stars 16 forks source link

Allow any keys by explicitly coercing them into strings #16

Closed dashed closed 8 years ago

dashed commented 8 years ago

I notice the internal hashing function is as follows: https://github.com/mattbierner/hamt/blob/88d054a27008976708f76c0ccb4e630e631e4b62/lib/hamt.js#L115-L125

This can be improved by explicitly converting any non-string keys into strings, which result in more representative hashes that otherwise hash to 0:

const hash = str => {
    if (typeof str === 'number')
        return str;

    str = typeof str === 'string' ? str : String(str);
    let hash = 0;
    for (let i = 0, len = str.length; i < len; ++i) {
        const c = str.charCodeAt(i);
        hash = (((hash << 5) - hash) + c) | 0;
    }
    return hash;
};

console.log(hash({})); // -1074417128
console.log(hash(Symbol())); // 1852627129
mattbierner commented 8 years ago

Damn, wrong change list number in the commit there. Will reopen.