Skip to content

Commit 5c5dc19

Browse files
committed
feat: Adding unique id generation
1 parent 897a4c2 commit 5c5dc19

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

templates/cli/lib/id.js.twig

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class ID {
2+
// Generate an hex ID based on timestamp
3+
// Recreated from https://www.php.net/manual/en/function.uniqid.php
4+
static #hexTimestamp() {
5+
const now = new Date();
6+
const sec = Math.floor(now.getTime() / 1000);
7+
const msec = now.getMilliseconds();
8+
9+
// Convert to hexadecimal
10+
const hexTimestamp = sec.toString(16) + msec.toString(16).padStart(5, '0');
11+
return hexTimestamp;
12+
}
13+
14+
static custom(id) {
15+
return id
16+
}
17+
18+
static unique(padding = 7) {
19+
// Generate a unique ID with padding to have a longer ID
20+
const baseId = ID.#hexTimestamp();
21+
let randomPadding = '';
22+
for (let i = 0; i < padding; i++) {
23+
const randomHexDigit = Math.floor(Math.random() * 16).toString(16);
24+
randomPadding += randomHexDigit;
25+
}
26+
return baseId + randomPadding;
27+
}
28+
}
29+
30+
module.exports = ID;

0 commit comments

Comments
 (0)