|
1
|
import crypto from "crypto"; |
|
2
|
|
|
3
|
export function generateCode( |
|
4
|
prefix: string = "GIFT", |
|
5
|
sections: number = 4 |
|
6
|
): string { |
|
7
|
// Characters to use (excluding similar-looking characters like 0/O, 1/I) |
|
8
|
const characters: string = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; |
|
9
|
|
|
10
|
// Calculate how many bytes we need for generating our code |
|
11
|
// We need enough random bytes to select from our character set |
|
12
|
const length: number = sections * 4; |
|
13
|
const byteLength: number = Math.ceil( |
|
14
|
(length * Math.log2(characters.length)) / 8 |
|
15
|
); |
|
16
|
|
|
17
|
// Generate random bytes |
|
18
|
const randomBytes: Buffer = crypto.randomBytes(byteLength); |
|
19
|
|
|
20
|
// Generate the code |
|
21
|
let code: string = ""; |
|
22
|
for (let i = 0; i < length; i++) { |
|
23
|
// Use a modulo operation to select a character from our set |
|
24
|
const randomIndex: number = |
|
25
|
randomBytes[i % randomBytes.length] % characters.length; |
|
26
|
code += characters.charAt(randomIndex); |
|
27
|
} |
|
28
|
|
|
29
|
// Split into chunks of 4 characters |
|
30
|
const chunks: string[] = []; |
|
31
|
for (let i = 0; i < code.length; i += 4) { |
|
32
|
chunks.push(code.slice(i, i + 4)); |
|
33
|
} |
|
34
|
|
|
35
|
// Format with prefix |
|
36
|
return prefix ? `${prefix}-${chunks.join("-")}` : chunks.join("-"); |
|
37
|
} |