Skip to content

Commit

Permalink
feat: rework random.numeric
Browse files Browse the repository at this point in the history
Co-authored-by: ST-DDT <ST-DDT@gmx.de>
  • Loading branch information
Shinigami92 and ST-DDT committed Apr 8, 2022
1 parent 46dbada commit 6bad0b5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/random.ts
Original file line number Diff line number Diff line change
Expand Up @@ -577,9 +577,15 @@ export class Random {
.join('')
: '';

const allowedDigits = '0123456789'
.split('')
.filter((digit) => !joinedBannedDigits.includes(digit));

if (
joinedBannedDigits === '0123456789' ||
(!allowLeadingZeros && joinedBannedDigits.endsWith('123456789'))
allowedDigits.length === 0 ||
(allowedDigits.length === 1 &&
!allowLeadingZeros &&
allowedDigits[0] === '0')
) {
throw new FakerError(
'Unable to generate numeric string, because all possible digits are banned.'
Expand All @@ -589,15 +595,13 @@ export class Random {
let result = '';

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

while (result.length < length) {
const digit = String(this.faker.datatype.number({ min: 0, max: 9 }));
if (bannedDigits.includes(digit)) {
continue;
}
result += digit;
result += this.arrayElement(allowedDigits);
}

return result;
Expand Down
9 changes: 9 additions & 0 deletions test/random.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,15 @@ describe('random', () => {
)
);
});

it('should ban all digits pass via bannedDigits', () => {
const actual = faker.random.numeric(1000, {
bannedDigits: 'c84U1'.split(''),
});

expect(actual).toHaveLength(1000);
expect(actual).toMatch(/^[0235679]{1000}$/);
});
});

describe('deprecation warnings', () => {
Expand Down

0 comments on commit 6bad0b5

Please sign in to comment.