Skip to content

Instantly share code, notes, and snippets.

@mikaelvesavuori
Created April 22, 2024 10:06
Show Gist options
  • Save mikaelvesavuori/0d6dc18d5ec974d2aa81b0d69818d682 to your computer and use it in GitHub Desktop.
Save mikaelvesavuori/0d6dc18d5ec974d2aa81b0d69818d682 to your computer and use it in GitHub Desktop.
A keylist generator that can produce 1000 conflict-free keys in less than 3200 bytes.
export function keylistGenerator() {
const bytes = (str: string) => new Blob([str]).size;
const newId = () => randomBytes(3).toString('hex');
//const newId = () => randomBytes(5).toString('base64').substring(0, 6);
function generateIdString() {
const keylist: string[] = [];
let generatedIds = 0;
function generate() {
let id = newId();
while (keylist.includes(id)) id = newId();
keylist.push(id);
generatedIds++;
}
while (generatedIds < 1000) generate();
return keylist.toString().replaceAll(',', '');
}
// @see https://zelark.github.io/nano-id-cc/: [6 characters] ~2 days or 37K IDs needed, in order to have a 1% probability of at least one collision.
function toList(str: string, idLength = 6) {
const keylist = [];
for (let i = 0; i < str.length; i += idLength) {
const block = str.substring(i, i + idLength);
keylist.push(block);
}
return keylist;
}
const generated = generateIdString();
const compressed = gzipSync(generated);
const list = toList(generated);
console.log(`The generated string is ${generated.length} characters long.`);
console.log(
`The original string was ${bytes(generated)} bytes and the compressed string was ${bytes(compressed.toString())} bytes.`
);
console.log(`The list is ${list.length} items long - the first value is "${list[0]}".`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment