teg*_*ggy 15 javascript node.js
我想生成一个简短的唯一字母数字值,用作在线购买的确认码.我正在研究https://github.com/broofa/node-uuid,但他们的uuids太长了,我想让它们长约8个字符.我能做到这一点的最佳方式是什么?
Jam*_*ore 36
在这个问题上稍晚一点,但看起来像hashids在这种情况下会很好用.
https://github.com/ivanakimov/hashids.node.js
hashids(哈希ID)从无符号整数创建短的,唯一的,可解密的哈希值
var Hashids = require('hashids'),
hashids = new Hashids('this is my salt');
var hash = hashids.encrypt(12345);
// hash is now 'ryBo'
var numbers = hashids.decrypt('ryBo');
// numbers is now [ 12345 ]
Run Code Online (Sandbox Code Playgroud)
如果你想要你可以做的约8个字符,下面要求至少8个字符.
hashids = new Hashids("this is my salt", 8);
Run Code Online (Sandbox Code Playgroud)
这个:
hash = hashids.encrypt(1);
// hash is now 'b9iLXiAa'
Run Code Online (Sandbox Code Playgroud)
接受的答案是可预测/可猜测的,这种解决方案应该是独特且不可预测的.
Wes*_*son 35
2015年10月23日:请参阅下面的hashids答案!
您可以借用URL缩短器模型并执行以下操作:
(100000000000).toString(36);
// produces 19xtf1ts
(200000000000).toString(36);
// produces 2jvmu3nk
Run Code Online (Sandbox Code Playgroud)
只需增加数字即可保持唯一:
function(uniqueIndex) {
return uniqueIndex.toString(36);
}
Run Code Online (Sandbox Code Playgroud)
请注意,这仅对"单实例"服务非常有用,因为它不介意按此方式排序(通过基本增量)的一定量的可预测性.如果您需要在多个应用程序/数据库实例中拥有真正独特的值,那么您应该根据某些注释考虑更全面的选项.