class Ids {
constructor() {
this.minNum = 10000000; // 最小值
this.maxNum = 99999999; // 最大值
this.numMap = {}; // 已经生成的数字
}
random(lower, upper) { // 范围数字 [low, upper]
return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}
getCount() { // 已经生成个数
var i = 0;
for (var key in this.numMap) {
i++;
}
return i;
}
generateOneId() {
if (this.getCount() >= (this.maxNum - this.minNum + 1)) { // 所有数字都用完
return null;
}
var num = this.random(this.minNum, this.maxNum);
while (this.numMap[num]) { // 找到没有产生的数字
num++;
if(num > this.maxNum){
num = this.minNum;
}
}
this.numMap[num] = 1; // 已经使用
return num;
}
reUse(num){ // 回收数字
delete this.numMap[num];
}
}
// -----测试用例
var ids = new Ids();
for(var i = 0; i < 100; i++){
console.log(ids.generateOneId());
}
/*
79272785
39219102
30413139
11701436
46959760
25798352
91950273
95401756
93811263
44627418
63875500
98773959
61721935
77552492
53432540
75034653
74016040
65816690
69063999
37930928
69574898
44329337
61744681
78300022
61310294
68391068
30771419
95961409
73453876
34559940
69108364
29473715
34555245
49424619
98996630
99880068
64500098
57692733
72389868
70941725
67430661
19177147
35135794
11054325
62052549
62815592
16789572
81021915
67777710
38006708
15498447
76629237
32855837
23543093
88652058
63294821
18157827
31047856
88904449
60327659
22329379
18860459
52758490
27456285
44136484
82098643
37079658
90022253
81876335
88957795
95281317
78929502
84713691
89514352
77665368
99012591
80789070
69209868
95239432
30468580
26736513
29376312
33594708
92441472
82269859
69898907
24734316
81440795
61861208
94795250
91560746
73637498
56739382
32772272
41386398
76608279
63826418
18603472
44424534
57588865
*/