生成随机ID且唯一
var T = [{P:11,G:2},
{P:101,G:7},
{P:1009,G:26},
{P:10007,G:59},
{P:100003,G:242},
{P:1000003,G:568},
{P:10000019,G:1792},
{P:100000007,G:5649},
{P:2147483647,G:16807},
]
// bits 为位数
function RandUnique(bits){
let t = T;
if(!t) {
throw Error('bits >= 1and bits <= 9');
}
this.p = t.P;
this.g = t.G;
this.seed = t.G;
this.n = 10**bits-1;
}
RandUnique.prototype.next = function(){
let seed = this.seed;
seed = (this.g * seed) % this.p;
while( seed > this.n)
seed = (this.g * seed) % this.p;
this.seed = seed;
return seed;
}
let ru = new RandUnique(2);
for(let i=0;i<100;i++){
console.log(ru.next());
}
运行结果:
文档来源:51CTO技术博客https://blog.51cto.com/dzqdzq/3230492
页:
[1]