Skip to content

Commit

Permalink
fix: empty array passed into helpers.arrayElements (#921)
Browse files Browse the repository at this point in the history
  • Loading branch information
c0per committed May 4, 2022
1 parent 788af82 commit 100a1ea
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/modules/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -783,7 +783,10 @@ export class Helpers {
count?: number
): T[] {
if (typeof count !== 'number') {
count = this.faker.datatype.number({ min: 1, max: array.length });
count =
array.length === 0
? 0
: this.faker.datatype.number({ min: 1, max: array.length });
} else if (count > array.length) {
count = array.length;
} else if (count < 0) {
Expand Down
12 changes: 12 additions & 0 deletions test/helpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,18 @@ describe('helpers', () => {
// Check uniqueness
expect(subset).toHaveLength(new Set(subset).size);
});

it('should return an empty array when receiving an empty array', () => {
const result = faker.helpers.arrayElements([]);

expect(result).toHaveLength(0);
});

it('should return an empty array when receiving an empty array and count > 0', () => {
const result = faker.helpers.arrayElements([], 3);

expect(result).toHaveLength(0);
});
});

describe('randomize()', () => {
Expand Down

0 comments on commit 100a1ea

Please sign in to comment.