碎片時(shí)間學(xué)編程「288]:將字符串哈希為數(shù)字

將輸入字符串散列為整數(shù)。
使用String.prototype.split()和Array.prototype.reduce()方法創(chuàng)建輸入字符串的散列,利用位移。
const sdbm = str => { ?let arr = str.split(''); ?return arr.reduce( ? ?(hashCode, currentVal) => ? ? ?(hashCode = ? ? ? ?currentVal.charCodeAt(0) + ? ? ? ?(hashCode << 6) + ? ? ? ?(hashCode << 16) - ? ? ? ?hashCode), ? ?0 ?);};
示例:
sdbm('name'); // -3521204949
更多內(nèi)容請(qǐng)?jiān)L問我的網(wǎng)站:https://www.icoderoad.com
標(biāo)簽: