Skip to content

Commit

Permalink
feat(package): random string/int utility functions
Browse files Browse the repository at this point in the history
  • Loading branch information
thelindat committed Jan 17, 2024
1 parent c0832cb commit 4bf5bb9
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions package/shared/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('');
}

0 comments on commit 4bf5bb9

Please sign in to comment.