几个常用字符串hash算法的node封装
发布于 4年前 作者 qingdu 3834 次浏览 最后一次编辑是 3年前

为下一步开发做的一些技术储备


把一些常用的字符串hash算法做了一下封装


代码如下




// hash.js
exports.additive = function (key, prime) {
key = key instanceof Buffer ? key : new Buffer(key);
prime = prime == undefined ? 0xffffffff : prime;
for (var hash = key.length, i = 0; i < key.length; i++) {
hash += key[i];
}
return (hash % prime);
}

exports.rotating = function(key) {
key = key instanceof Buffer ? key : new Buffer(key);
for (var hash = key.length, i = 0; i<key.length; ++i) {
hash = (hash << 4) ^ (hash >> 28) ^ key[i];
}
return hash;
}

exports.bernstein = function(key, prime) {
key = key instanceof Buffer ? key : new Buffer(key);
prime = prime == undefined ? 0xffffffff : prime;
var hash = 0;
for (i=0; i<key.length; ++i) {
hash = (hash << 5 + hash) + key[i];
}
return hash;
}

exports.fnv = function (key){
key = key instanceof Buffer ? key : new Buffer(key);
var p = 16777619, hash = 0x811C9DC5;
for(var i=0; i< key.length; i++) {
hash = (hash * p) ^ key[i];
}
hash += hash << 13;
hash ^= hash >> 7;
hash += hash << 3;
hash ^= hash >> 17;
hash += hash << 5;
return hash;
}

exports.fnv1a = function (key){
key = key instanceof Buffer ? key : new Buffer(key);
var p = 16777619, hash = 0x811C9DC5;
for(var i=0; i< key.length; i++) {
hash = (hash ^ key[i]) * p;
}
hash += hash << 13;
hash ^= hash >> 7;
hash += hash << 3;
hash ^= hash >> 17;
hash += hash << 5;
return hash;
}
4 回复

bernstein/time33算法在PHP里有个改进,它把初始的hash值改成了 5381(001 010 100 000 101),据说hash后的分布更好一些.

这个数字还集 素数、奇数和缺数于一身,膜拜!

写这个的时候考虑过几个常用的33常数
33, 131, 1313, 5381之类的这些,
不过从位运算角度考虑, 还是33合适

乘33没错,var hash = 0; 这个初始值PHP给的是5381

回到顶部