Created
December 23, 2021 07:57
-
-
Save shijiatongxue/34011ac97078998950d98b4cc7b031f3 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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