Monorepo for Aesthetic.Computer
aesthetic.computer
1// generate-code.mjs
2// Short code generator for paintings
3// Uses nanoid with custom alphabet for pronounceable, collision-resistant codes
4
5import { customAlphabet } from 'nanoid';
6
7// Base alphabet - lowercase preferred (3x) but uppercase included for more space
8// Mix consonants, vowels, and numbers for better distribution
9const consonants = 'bcdfghjklmnpqrstvwxyz' + 'bcdfghjklmnpqrstvwxyz' + 'BCDFGHJKLMNPQRSTVWXYZ';
10const vowels = 'aeiou' + 'aeiou' + 'AEIOU';
11const numbers = '23456789'; // Exclude 0,1 (look like O,l)
12
13// Configurable settings
14const CODE_LENGTH = 3; // Start with 3 chars, can grow
15const MAX_ATTEMPTS = 100; // Collision retry limit
16
17// Create nanoid generator with lowercase-only alphabet
18const alphabet = consonants + vowels + numbers;
19const nanoid = customAlphabet(alphabet, CODE_LENGTH);
20
21/**
22 * Generate a pronounceable short code
23 * Pattern: consonant-vowel-consonant for better pronunciation
24 * Example: "waf", "bop", "zet"
25 */
26export function generateCode(existingCodes = new Set()) {
27 let attempts = 0;
28
29 while (attempts < MAX_ATTEMPTS) {
30 const code = nanoid();
31
32 // Check for collision
33 if (!existingCodes.has(code)) {
34 existingCodes.add(code);
35 return code;
36 }
37
38 attempts++;
39 }
40
41 // If we hit max attempts, use longer code
42 const longerNanoid = customAlphabet(alphabet, CODE_LENGTH + 1);
43 return longerNanoid();
44}
45
46/**
47 * Generate multiple codes in batch
48 * More efficient for migrations
49 */
50export function generateCodes(count, existingCodes = new Set()) {
51 const codes = [];
52
53 for (let i = 0; i < count; i++) {
54 codes.push(generateCode(existingCodes));
55 }
56
57 return codes;
58}
59
60/**
61 * Check if a code is pronounceable (has vowel balance)
62 * For validation/testing
63 */
64export function isPronounceableCode(code) {
65 const hasVowel = /[aeiou]/.test(code);
66 const hasConsonant = /[bcdfghjklmnpqrstvwxyz]/.test(code);
67 return hasVowel && hasConsonant;
68}