Skip to content

Instantly share code, notes, and snippets.

@y0n1
Created November 17, 2019 15:31
Show Gist options
  • Save y0n1/3b27d670aa561b7f4467ed3ddfec8ebe to your computer and use it in GitHub Desktop.
Save y0n1/3b27d670aa561b7f4467ed3ddfec8ebe to your computer and use it in GitHub Desktop.
Short hash generator with collision checking
const letters = 'abcdefghijklmnopqrstuvwxyz';
const numbers = '1234567890';
const charset = letters + letters.toUpperCase() + numbers;
function pickRandomElement(array) {
const { floor, random } = Math;
return array[floor(random() * array.length)];
}
function randomString(length) {
const { cache } = randomString;
while (true) {
let uid = '';
for (let i = 0; i < length; i++) {
uid += pickRandomElement(charset);
}
if (!cache.has(uid)) {
cache.add(uid);
return uid;
}
}
}
randomString.cache = new Set();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment