Improves random generation (#251)

pull/247/head
Alex Kern 9 months ago committed by GitHub
parent 770dd8ee98
commit e64da0f32c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -38,7 +38,7 @@ async function generateShortSlugUntilUnique(
checkExists: (key: string) => Promise<boolean>,
): Promise<string> {
for (let i = 0; i < config.shortSlug.maxAttempts; i++) {
const slug = generateShortSlug()
const slug = await generateShortSlug()
const exists = await checkExists(getShortSlugKey(slug))
if (!exists) {
return slug

@ -25,12 +25,17 @@ function generateRandomWords(
}
const getRandomInt = (max: number): number => {
const buffer = new Uint32Array(1)
if (typeof window !== 'undefined' && window.crypto) {
window.crypto.getRandomValues(buffer)
} else {
crypto.randomFillSync(buffer)
}
const limit = 4294967295 - (4294967295 % max) // uint32 max
let buffer = new Uint32Array(1)
do {
if (typeof window !== 'undefined' && window.crypto) {
window.crypto.getRandomValues(buffer)
} else {
crypto.randomFillSync(buffer)
}
} while (buffer[0] >= limit)
return buffer[0] % max
}
@ -44,15 +49,12 @@ function generateRandomWords(
})
}
export const generateShortSlug = (): string => {
let result = ''
for (let i = 0; i < config.shortSlug.numChars; i++) {
result +=
config.shortSlug.chars[
Math.floor(Math.random() * config.shortSlug.chars.length)
]
}
return result
export const generateShortSlug = async (): Promise<string> => {
const parts = await generateRandomWords(
config.shortSlug.chars.split(''),
config.shortSlug.numChars,
)
return parts.join('')
}
export const generateLongSlug = async (): Promise<string> => {

Loading…
Cancel
Save