登录
注册
node.js 学习社区
几个常用字符串hash算法的node封装

任重道远

2014-12-01 01:44


为下一步开发做的一些技术储备
把一些常用的字符串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;
} 

原文引自:http://cnodejs.org/topic/4f16442ccae1f4aa2700114d

回复 · 0

发表回复

你可以在回复中 @ 其他人