gen-unique.ts
February 15, 2021•137 words
/**
* A function that generates a unique ID
* Made up of N random characters, N numbers from end of timestamp, and shuffled using Math.random
* Due to the low entropey that Math.random provides, this is not appropriate for anything security-related
*/
export default (totalLen: number = 5) => {
// 1. Generate Random Characters
const letters = (len: number, str: string = ''): string => {
const newStr = () =>
String.fromCharCode(65 + Math.floor(Math.random() * 26));
return len <= 1 ? str : str + letters(len - 1, str + newStr());
};
// 2. Generate random numbers (based on time in milliseconds)
const numbers = (len: number) =>
Date.now()
.toString()
.substr(-len);
// 3. Shuffle order, with a multiplier of JavaScript's Math.random
return (letters(totalLen) + numbers(totalLen))
.split('')
.sort(() => 0.5 - Math.random())
.join('');
};