@augment-vir/common
Version:
A collection of augments, helpers types, functions, and classes for any JavaScript environment.
96 lines (95 loc) • 1.63 kB
JavaScript
import { randomInteger } from './random-integer.js';
/**
* All letters allowed in {@link randomString}.
*
* @category Random : Util
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export const allowedRandomStringLetters = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'-',
'_',
];
/**
* Creates a random string (including letters and numbers) of a given length.
*
* This function uses cryptographically secure randomness.
*
* @category Random
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function randomString(generatedStringLength = 16) {
let stringBuilder = '';
for (let i = 0; i < generatedStringLength; i++) {
const index = randomInteger({
min: 0,
max: allowedRandomStringLetters.length - 1,
});
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
stringBuilder += allowedRandomStringLetters[index];
}
return stringBuilder;
}