生成随机ID且唯一

 1 var T = [
 2     {P:11,G:2},
 3     {P:101,G:7},
 4     {P:1009,G:26},
 5     {P:10007,G:59},
 6     {P:100003,G:242},
 7     {P:1000003,G:568},
 8     {P:10000019,G:1792},
 9     {P:100000007,G:5649},
10     {P:2147483647,G:16807},
11 ]
12 
13 // bits 为位数
14 function RandUnique(bits){
15     let t = T[bits-1];
16     if(!t) {
17         throw Error('bits >= 1  and bits <= 9');
18     }
19 
20     this.p = t.P;
21     this.g = t.G;
22     this.seed = t.G;
23     this.n = 10**bits-1;
24 }
25 
26 RandUnique.prototype.next = function(){
27     let seed = this.seed;
28     seed = (this.g * seed) % this.p;
29     while( seed > this.n)
30         seed = (this.g * seed) % this.p;
31     
32     this.seed = seed;
33     return seed;
34 }
35 
36 
37 let ru = new RandUnique(2);
38 for(let i=0;i<100;i++){
39     console.log(ru.next());
40 }

运行结果:

猜你喜欢

转载自www.cnblogs.com/dzqdzq/p/11001395.html