-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrobot-name.js
83 lines (61 loc) · 1.83 KB
/
robot-name.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
function* uuidGenerator(maxNumUuids) {
let uuids = [];
const lazyLoadAt = (map, index) => {
if (map[index] === undefined) map[index] = index;
};
const getFisherYatesSwapIndex = (arrayLength, currentIndex) =>
Math.floor((arrayLength - currentIndex) * Math.random() + currentIndex);
for (let i = 0; i < maxNumUuids; i++) {
const randomIndex = getFisherYatesSwapIndex(maxNumUuids, i);
lazyLoadAt(uuids, i);
lazyLoadAt(uuids, randomIndex);
[uuids[i], uuids[randomIndex]] = [uuids[randomIndex], uuids[i]];
yield uuids[i];
}
}
class RobotUuidGenerator {
constructor() {
this.reset();
}
next() {
const cur = this._uuidGenerator.next();
if (cur.done) {
throw new Error("No more available UUIDs");
}
return cur.value;
}
reset() {
this._uuidGenerator = RobotUuidGenerator.createUuidGenerator();
}
static createUuidGenerator() {
return uuidGenerator(26 * 26 * 10 * 10 * 10);
}
}
const robotUuidGenerator = new RobotUuidGenerator();
export class Robot {
constructor() {
this.reset();
}
get name() {
return Robot.formatUuid(this._uuid);
}
reset() {
this._uuid = robotUuidGenerator.next();
}
static releaseNames() {
robotUuidGenerator.reset();
}
static decodeUuid(uuid) {
const l1 = Math.floor(uuid / 26000);
const l2 = Math.floor((uuid - l1 * 26000) / 1000);
const d1 = Math.floor((uuid - (l1 * 26000 + l2 * 1000)) / 100);
const d2 = Math.floor((uuid - (l1 * 26000 + l2 * 1000 + d1 * 100)) / 10);
const d3 = Math.floor(uuid - (l1 * 26000 + l2 * 1000 + d1 * 100 + 10 * d2));
return [l1, l2, d1, d2, d3];
}
static formatUuid(uuid) {
const [l1, l2, d1, d2, d3] = Robot.decodeUuid(uuid);
const formatL = l => String.fromCharCode(65 + l);
return `${formatL(l1)}${formatL(l2)}${d1}${d2}${d3}`;
}
}