Skip to content

Instantly share code, notes, and snippets.

@Lissy93
Created December 19, 2019 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lissy93/9da07fe8b877801f7814424a00acbe90 to your computer and use it in GitHub Desktop.
Save Lissy93/9da07fe8b877801f7814424a00acbe90 to your computer and use it in GitHub Desktop.
A simple TypeScript function: Generates a random alpha-numeric ID with length of N
/**
* A function that generates a unique ID
* Made up of N random characters, N numbers from end of timestamp, and shuffled using Math.random
*/
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('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment