Created
August 30, 2022 05:59
-
-
Save luigircruz/303d1e950ec6fe6e7ec46664de89db0f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * Replace backslash to slash | |
| * | |
| * @category String | |
| */ | |
| export function slash(str: string) { | |
| return str.replace(/\\/g, '/') | |
| } | |
| /** | |
| * Ensure prefix of a string | |
| * | |
| * @category String | |
| */ | |
| export function ensurePrefix(prefix: string, str: string) { | |
| if (!str.startsWith(prefix)) | |
| return prefix + str | |
| return str | |
| } | |
| /** | |
| * Ensure suffix of a string | |
| * | |
| * @category String | |
| */ | |
| export function ensureSuffix(suffix: string, str: string) { | |
| if (!str.endsWith(suffix)) | |
| return str + suffix | |
| return str | |
| } | |
| /** | |
| * Dead simple template engine, just like Python's `.format()` | |
| * | |
| * @category String | |
| * @example | |
| * ``` | |
| * const result = template( | |
| * 'Hello {0}! My name is {1}.', | |
| * 'Inès', | |
| * 'Anthony' | |
| * ) // Hello Inès! My name is Anthony. | |
| * ``` | |
| */ | |
| export function template(str: string, ...args: any[]): string { | |
| return str.replace(/{(\d+)}/g, (match, key) => { | |
| const index = Number(key) | |
| if (Number.isNaN(index)) | |
| return match | |
| return args[index] | |
| }) | |
| } | |
| // port from nanoid | |
| // https://github.com/ai/nanoid | |
| const urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' | |
| /** | |
| * Generate a random string | |
| * @category String | |
| */ | |
| export function randomStr(size = 16, dict = urlAlphabet) { | |
| let id = '' | |
| let i = size | |
| const len = dict.length | |
| while (i--) | |
| id += dict[(Math.random() * len) | 0] | |
| return id | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment