@grandom/string
Version:
A configurable, flexible, seedable, and overall great random string generator.
70 lines (66 loc) • 2.34 kB
JavaScript
;
var core = require('@grandom/core');
// TODO: implement edge cases (including infinite loops)
// TODO: implement detailed error handling
class RandomString extends core.RandomGenerator {
// ---------------------------------------------------------------------------
string(arg1, arg2, arg3) {
if (typeof arg1 !== 'undefined') {
let length = RandomString.DEFAULT_LENGTH;
if (typeof arg1 === 'number') {
length = arg1;
}
else if (typeof arg1 === 'object' && arg1 !== null) {
if (typeof arg1.length === 'number') {
length = arg1.length;
}
}
else {
if (typeof arg1 !== 'number') {
throw new TypeError(
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`length must be a number, got: ${arg1} (typeof === "${typeof arg1}").`);
}
}
// NaN check
// eslint-disable-next-line no-self-compare
if (length !== length) {
throw new RangeError(`length must be a non-NaN number, got: ${length}.`);
}
else if (length < 0 || length > Number.MAX_SAFE_INTEGER) {
throw new RangeError(`length must be >= 0 <= 2^53-1 (9,007,199,254,740,991), got ${length}.`);
}
if (length === 0) {
return '';
}
return this._engine.nextString(Math.floor(length), RandomString.ALPHANUMERIC);
}
return this._engine.nextString(RandomString.DEFAULT_LENGTH, RandomString.ALPHANUMERIC);
}
}
/**
* The default length of a random string.
*
* @default 16
*/
RandomString.DEFAULT_LENGTH = 16;
/**
* Numbers set.
*
* @default '0123456789'
*/
RandomString.NUMBERS = '0123456789';
/**
* Letters set.
*
* @default 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
*/
RandomString.LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
/**
* Letters and numbers.
*
* @default 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
*/
RandomString.ALPHANUMERIC = RandomString.LETTERS + RandomString.NUMBERS;
module.exports = RandomString;
//# sourceMappingURL=index.js.map