生成的哈希大小

问题描述

今天我按如下方式生成哈希:

const hashids = require('hashids');

const ALPHABET = "ABCDEFGHIJKLMnopQRSTUVWXYZ";

let number = 1419856
let hash = new hashids('Salto do Pedro',6,ALPHABET).encode(number)
console.log("Hash:",hash,". Number:",number,". Size:",hash.length)

所以控制台上打印的是:

[Running] node "c:\Users\pedro\Desktop\teste\testPedro.js"
Hash: YMMMMM . Number: 1419856 . Size: 6

[Done] exited with code=0 in 0.258 seconds

但是,如果我将变量“数字”更改为数字 1419857,结果是:

[Running] node "c:\Users\pedro\Desktop\teste\testPedro.js"
Hash: DRVVVVV . Number: 1419857 . Size: 7

[Done] exited with code=0 in 0.245 seconds

我的疑问是: 我正在使用的字母表有 26 个字符,我定义了 hashid 的最小大小为 6 个字符,我可以使用 6 个字符的最大 hashid 不会是 308.915.776 (26 * 26 * 26 * 26 * 26 * 26)? 为什么在数字 1.419.857 中他已经在我的 hashid 中增加一个字符?

解决方法

好问题。这可能看起来令人生畏,但我会尝试通过理解代码背后的数学原理使其尽可能简单。

Hashids 构造函数接受参数 - (salt,minLength,alphabet,sep)

Salt - String value which makes your ids unique in your project
MinLength - Number value which is the minimum length of id string you need
alphabet - String value (Input string)
seps - String value to take care of curse words

使用这个集合,它尝试创建一个包含 Salt 和随机字符(基于 salt、sep、alphabet 传递)的缓冲区数组,并打乱每个字符的位置。

现在,下面是根据上述字符数组对值进行编码的代码

id = []
do {
    id.unshift(alphabetChars[input % alphabetChars.length])
    input = Math.floor(input / alphabetChars.length)
} while (input > 0)

我们先来看例子1-

this.salt = 'Salto do Pedro'
this.minLength = 6
input = 1419856
// alphabetChars is the array which generates based on salt,alphabet and seps. (complex operations invol
alphabetChars = ["A","X","R","N","W","G","Q","O","L","D","V","Y","K","J","E","Z","M"]

Example 1

然后通过字符串连接最终数组,并在开头附加一个抽奖字符(另一个数学运算计算)。这作为编码字符串返回。

让我们先举个例子 2 -

this.salt = 'Salto do Pedro'
this.minLength = 6
input = 1419857
// alphabetChars is the array which generates based on salt,alphabet and seps. (complex operations invol
alphabetChars = ["V","M","A","X"]

Example 2

现在这就是为什么如果数字改变你会得到 +1 个额外字符的原因(因为它运行了一个额外的循环)。受监控的是字母数组的最小长度而不是最大长度,因此您不能确定总是 +1 个字符获得相同的长度。

希望有帮助。如果您想深入了解 - 这是库的代码 - https://github.com/niieani/hashids.js/blob/master/dist/hashids.js#L197