2

今天我生成哈希如下:

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 中增加了一个字符?

4

1 回答 1

3

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

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

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"]

示例 1

最后的数组然后由字符串连接,并在开头附加一个彩票字符(另一个数学运算 calc)。这作为编码字符串返回。

让我们先举个例子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","R","Y","W","J","G","M","L","Z","K","O","D","E","A","Q","N","X"]

示例 2

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

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

于 2020-12-28T18:04:27.533 回答