Skip to content

Commit

Permalink
fix(helpers): uniform distribution in helpers.arrayElements (#1770)
Browse files Browse the repository at this point in the history
  • Loading branch information
ST-DDT committed Jan 24, 2023
1 parent 3a44d5f commit 2b84b33
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 6 deletions.
3 changes: 2 additions & 1 deletion src/modules/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,8 +594,9 @@ export class HelpersModule {
let temp: T;
let index: number;

// Shuffle the last `count` elements of the array
while (i-- > min) {
index = Math.floor((i + 1) * this.faker.number.float({ max: 0.99 }));
index = this.faker.number.int(i);
temp = arrayCopy[index];
arrayCopy[index] = arrayCopy[i];
arrayCopy[i] = temp;
Expand Down
10 changes: 5 additions & 5 deletions test/__snapshots__/helpers.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -195,15 +195,15 @@ exports[`helpers > 1211 > arrayElements > noArgs 1`] = `

exports[`helpers > 1211 > arrayElements > with array 1`] = `
[
"r",
"d",
"o",
"l",
"r",
"!",
"l",
"d",
"W",
"H",
"W",
"e",
"l",
"o",
"l",
" ",
Expand All @@ -213,7 +213,7 @@ exports[`helpers > 1211 > arrayElements > with array 1`] = `
exports[`helpers > 1211 > arrayElements > with array and count 1`] = `
[
"r",
"o",
" ",
"!",
]
`;
Expand Down
39 changes: 39 additions & 0 deletions test/helpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,45 @@ describe('helpers', () => {

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

it('should return the only element in the array when there is only 1', () => {
const testArray = ['hello'];
const actual = faker.helpers.arrayElements(testArray);
expect(actual).toEqual(testArray);
});

it('should return each element with a somewhat equal distribution with 2 elements', () => {
const input = Array.from({ length: 2 }, (_, i) => i);
const occurrences = Array.from({ length: 2 }, () => 0);

for (let i = 0; i < 1000; i++) {
const [result] = faker.helpers.arrayElements(input, 1);
occurrences[result]++;
}

for (const occurrence of occurrences) {
expect(occurrence).toBeGreaterThanOrEqual(400);
expect(occurrence).toBeLessThanOrEqual(600);
}
});

it.each([10, 100, 1000])(
'should return each element with a somewhat equal distribution with %s elements',
(length) => {
const input = Array.from({ length }, (_, i) => i % 10);
const occurrences = Array.from({ length: 10 }, () => 0);

for (let i = 0; i < 1000; i++) {
const [result] = faker.helpers.arrayElements(input, 1);
occurrences[result]++;
}

for (const occurrence of occurrences) {
expect(occurrence).toBeGreaterThanOrEqual(70);
expect(occurrence).toBeLessThanOrEqual(130);
}
}
);
});

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

0 comments on commit 2b84b33

Please sign in to comment.