可以说我有一个字符串var input = "Foo",我需要该字符串中的100%唯一数字,我尝试了类似
for (var i = 0, len = input.length; i < len; i++) {
output += input[i].charCodeAt(0)
}
Run Code Online (Sandbox Code Playgroud)
但这会生成类似W8M和的重复项,YSM并且都返回的ID 149。
是否有类似这样的算法?
这是一个简单的字符串hash函数js。
function getHash(input){
var hash = 0, len = input.length;
for (var i = 0; i < len; i++) {
hash = ((hash << 5) - hash) + input.charCodeAt(i);
hash |= 0; // to 32bit integer
}
return hash;
}
console.log(getHash("YSM"));
console.log(getHash("W8M"));Run Code Online (Sandbox Code Playgroud)
这个怎么样:
String.prototype.hashCode = function() {
var hash = 0, i, chr, len;
if (this.length === 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
Run Code Online (Sandbox Code Playgroud)
我从 npm 找到了一个名为seedrandom.
这是它的示例用法:
seedrandom("YSM").quick()
// Always 0.25078649865463376
seedrandom("W8M").quick()
// Always 0.6935836656484753
Run Code Online (Sandbox Code Playgroud)