【问题标题】:Generated hashid size生成的哈希大小
【发布时间】:2021-04-05 10:09:25
【问题描述】:

今天我生成 hashid 如下:

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

【问题讨论】:

    标签: javascript encode hashids


    【解决方案1】:

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

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

    最后的数组然后由字符串连接,并在开头附加一个彩票字符(另一个数学运算 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"]
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-08
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2014-02-24
      • 1970-01-01
      相关资源
      最近更新 更多