Created
November 17, 2019 15:31
-
-
Save y0n1/3b27d670aa561b7f4467ed3ddfec8ebe to your computer and use it in GitHub Desktop.
Short hash generator with collision checking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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