Skip to content

Commit 6bad0b5

Browse files
Shinigami92ST-DDT
andcommitted
feat: rework random.numeric
Co-authored-by: ST-DDT <ST-DDT@gmx.de>
1 parent 46dbada commit 6bad0b5

2 files changed

Lines changed: 21 additions & 8 deletions

File tree

src/random.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -577,9 +577,15 @@ export class Random {
577577
.join('')
578578
: '';
579579

580+
const allowedDigits = '0123456789'
581+
.split('')
582+
.filter((digit) => !joinedBannedDigits.includes(digit));
583+
580584
if (
581-
joinedBannedDigits === '0123456789' ||
582-
(!allowLeadingZeros && joinedBannedDigits.endsWith('123456789'))
585+
allowedDigits.length === 0 ||
586+
(allowedDigits.length === 1 &&
587+
!allowLeadingZeros &&
588+
allowedDigits[0] === '0')
583589
) {
584590
throw new FakerError(
585591
'Unable to generate numeric string, because all possible digits are banned.'
@@ -589,15 +595,13 @@ export class Random {
589595
let result = '';
590596

591597
if (!allowLeadingZeros && !bannedDigits.includes('0')) {
592-
result += this.faker.datatype.number({ min: 1, max: 9 });
598+
result += this.arrayElement(
599+
allowedDigits.filter((digit) => digit !== '0')
600+
);
593601
}
594602

595603
while (result.length < length) {
596-
const digit = String(this.faker.datatype.number({ min: 0, max: 9 }));
597-
if (bannedDigits.includes(digit)) {
598-
continue;
599-
}
600-
result += digit;
604+
result += this.arrayElement(allowedDigits);
601605
}
602606

603607
return result;

test/random.spec.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,15 @@ describe('random', () => {
349349
)
350350
);
351351
});
352+
353+
it('should ban all digits pass via bannedDigits', () => {
354+
const actual = faker.random.numeric(1000, {
355+
bannedDigits: 'c84U1'.split(''),
356+
});
357+
358+
expect(actual).toHaveLength(1000);
359+
expect(actual).toMatch(/^[0235679]{1000}$/);
360+
});
352361
});
353362

354363
describe('deprecation warnings', () => {

0 commit comments

Comments
 (0)