feat(package): random string/int utility functions

This commit is contained in:
Linden
2024-01-17 17:43:08 +11:00
parent c0832cbe72
commit 4bf5bb9430

View File

@@ -38,3 +38,53 @@ export async function waitFor<T>(cb: () => T, errMessage: string | void, timeout
return p;
}
export function getRandomInt(min = 0, max = 9) {
if (min > max) [min, max] = [max, min];
return Math.floor(Math.random() * (max - min + 1)) + min;
}
export function getRandomChar(lowercase?: boolean) {
const str = String.fromCharCode(getRandomInt(65, 90));
return lowercase ? str.toLowerCase() : str;
}
export function getRandomAlphanumeric(lowercase?: boolean) {
return Math.random() > 0.5 ? getRandomChar(lowercase) : getRandomInt();
}
const formatChar: Record<string, (...args: any) => string | number> = {
'1': getRandomInt,
A: getRandomChar,
'.': getRandomAlphanumeric,
a: getRandomChar,
};
export function getRandomString(pattern: string, length?: number): string {
const len = length || pattern.replace(/\^/g, '').length;
const arr: Array<string | number> = Array(len).fill(0);
let size = 0;
let i = 0;
while (size < len) {
i += 1;
let char: string | number = pattern.charAt(i - 1);
if (char === '') {
arr[size] = ' '.repeat(len - size);
break;
} else if (char === '^') {
i += 1;
char = pattern.charAt(i - 1);
} else {
const fn = formatChar[char];
char = fn ? fn(char === 'a') : char;
}
size += 1;
arr[size - 1] = char;
}
return arr.join('');
}