diff options
| author | Shinigami <[email protected]> | 2022-04-24 19:12:37 +0200 |
|---|---|---|
| committer | GitHub <[email protected]> | 2022-04-24 19:12:37 +0200 |
| commit | 712b1de126ea6580660a320e065c35ac775f09b3 (patch) | |
| tree | 34751e91f1fa59c8be98685b4f58140bad1755ea /src | |
| parent | f797b6310ea73c8ab5637ed415faab221115ea30 (diff) | |
| download | faker-712b1de126ea6580660a320e065c35ac775f09b3.tar.xz faker-712b1de126ea6580660a320e065c35ac775f09b3.zip | |
feat: random numeric (#797)
Co-authored-by: ST-DDT <[email protected]>
Diffstat (limited to 'src')
| -rw-r--r-- | src/random.ts | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/src/random.ts b/src/random.ts index 96128dd5..c349c92f 100644 --- a/src/random.ts +++ b/src/random.ts @@ -528,6 +528,64 @@ export class Random { } /** + * Generates a given length string of digits. + * + * @param length The number of digits to generate. Defaults to `1`. + * @param options The options to use. Defaults to `{}`. + * @param options.allowLeadingZeros If true, leading zeros will be allowed. Defaults to `false`. + * @param options.bannedDigits An array of digits which should be banned in the generated string. Defaults to `[]`. + * + * @example + * faker.random.numeric() // '2' + * faker.random.numeric(5) // '31507' + * faker.random.numeric(42) // '56434563150765416546479875435481513188548' + * faker.random.numeric(42, { allowLeadingZeros: true }) // '00564846278453876543517840713421451546115' + * faker.random.numeric(6, { bannedDigits: ['0'] }) // '943228' + */ + numeric( + length: number = 1, + options: { + allowLeadingZeros?: boolean; + bannedDigits?: readonly string[]; + } = {} + ): string { + if (length <= 0) { + return ''; + } + + const { allowLeadingZeros = false, bannedDigits = [] } = options; + + const allowedDigits = '0123456789' + .split('') + .filter((digit) => !bannedDigits.includes(digit)); + + if ( + allowedDigits.length === 0 || + (allowedDigits.length === 1 && + !allowLeadingZeros && + allowedDigits[0] === '0') + ) { + throw new FakerError( + 'Unable to generate numeric string, because all possible digits are banned.' + ); + } + + let result = ''; + + if (!allowLeadingZeros && !bannedDigits.includes('0')) { + result += this.arrayElement( + allowedDigits.filter((digit) => digit !== '0') + ); + } + + while (result.length < length) { + result += this.arrayElement(allowedDigits); + } + + return result; + } + + /** * Returns a hexadecimal number. * * @param count Length of the generated number. Defaults to `1`. |
