Skip to content

Instantly share code, notes, and snippets.

@shijiatongxue
Created December 23, 2021 07:57
Show Gist options
  • Save shijiatongxue/34011ac97078998950d98b4cc7b031f3 to your computer and use it in GitHub Desktop.
Save shijiatongxue/34011ac97078998950d98b4cc7b031f3 to your computer and use it in GitHub Desktop.
/**
* Get a random id with prefix, it not strictly guarantee id uniqueness
*
* Note: the return value of getUuid is too long, we need a short one
*
* @example
* getUuidShort({ prefix: 'semi' }) => 'semi-46dinzc'
* getUuidShort({ prefix: '' }) => '0eer2i0'
* getUuidShort({ prefix: 'semi', length: 4 }) => 'semi-8jts'
*/
function getUuidShort({ prefix = '', length = 7 }: { prefix?: string; length?: number }) {
const characters = '0123456789abcdefghijklmnopqrstuvwxyz';
const total = characters.length;
let randomId = '';
for (let i = 0; i < length; i++) {
const random = Math.floor(Math.random() * total);
randomId += characters.charAt(random);
}
return prefix ? `${prefix}-${randomId}` : randomId;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment