Skip to content

refactor: move some random methods to helpers #892

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
May 1, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 60 additions & 2 deletions src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,11 @@ export class Helpers {
): T {
deprecated({
deprecated: 'faker.helpers.randomize()',
proposed: 'faker.random.arrayElement()',
proposed: 'faker.helpers.arrayElement()',
// since: 'v5.0.0', (?)
until: 'v7.0.0',
});
return this.faker.random.arrayElement(array);
return this.faker.helpers.arrayElement(array);
}

/**
Expand Down Expand Up @@ -742,4 +742,62 @@ export class Helpers {
const key = this.faker.helpers.objectKey(object);
return object[key];
}

/**
* Returns random element from the given array.
*
* @template T The type of the entries to pick from.
* @param array Array to pick the value from.
*
* @example
* faker.helpers.arrayElement(['cat', 'dog', 'mouse']) // 'dog'
*/
arrayElement<T = string>(array: ReadonlyArray<T>): T {
const index =
array.length > 1
? this.faker.datatype.number({ max: array.length - 1 })
: 0;

return array[index];
}

/**
* Returns a subset with random elements of the given array in random order.
*
* @template T The type of the entries to pick from.
* @param array Array to pick the value from. Defaults to `['a', 'b', 'c']`.
* @param count Number of elements to pick.
* When not provided, random number of elements will be picked.
* When value exceeds array boundaries, it will be limited to stay inside.
*
* @example
* faker.helpers.arrayElements(['cat', 'dog', 'mouse']) // ['mouse', 'cat']
* faker.helpers.arrayElements([1, 2, 3, 4, 5], 2) // [4, 2]
*/
arrayElements<T>(array: ReadonlyArray<T>, count?: number): T[] {
if (typeof count !== 'number') {
count = this.faker.datatype.number({ min: 1, max: array.length });
} else if (count > array.length) {
count = array.length;
} else if (count < 0) {
count = 0;
}

const arrayCopy = array.slice(0);
let i = array.length;
const min = i - count;
let temp: T;
let index: number;

while (i-- > min) {
index = Math.floor(
(i + 1) * this.faker.datatype.float({ min: 0, max: 0.99 })
);
temp = arrayCopy[index];
arrayCopy[index] = arrayCopy[i];
arrayCopy[i] = temp;
}

return arrayCopy.slice(min);
}
}
48 changes: 18 additions & 30 deletions src/random.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,16 +104,19 @@ export class Random {
* @example
* faker.random.arrayElement() // 'b'
* faker.random.arrayElement(['cat', 'dog', 'mouse']) // 'dog'
*
* @deprecated
*/
arrayElement<T = string>(
array: ReadonlyArray<T> = ['a', 'b', 'c'] as unknown as ReadonlyArray<T>
): T {
const index =
array.length > 1
? this.faker.datatype.number({ max: array.length - 1 })
: 0;

return array[index];
deprecated({
deprecated: 'faker.random.arrayElement()',
proposed: 'faker.helpers.arrayElement()',
since: 'v6.3.0',
until: 'v7.0.0',
});
return this.faker.helpers.arrayElement(array);
}

/**
Expand All @@ -129,35 +132,20 @@ export class Random {
* faker.random.arrayElements() // ['b', 'c']
* faker.random.arrayElements(['cat', 'dog', 'mouse']) // ['mouse', 'cat']
* faker.random.arrayElements([1, 2, 3, 4, 5], 2) // [4, 2]
*
* @deprecated
*/
arrayElements<T>(
array: ReadonlyArray<T> = ['a', 'b', 'c'] as unknown as ReadonlyArray<T>,
count?: number
): T[] {
if (typeof count !== 'number') {
count = this.faker.datatype.number({ min: 1, max: array.length });
} else if (count > array.length) {
count = array.length;
} else if (count < 0) {
count = 0;
}

const arrayCopy = array.slice(0);
let i = array.length;
const min = i - count;
let temp: T;
let index: number;

while (i-- > min) {
index = Math.floor(
(i + 1) * this.faker.datatype.float({ min: 0, max: 0.99 })
);
temp = arrayCopy[index];
arrayCopy[index] = arrayCopy[i];
arrayCopy[i] = temp;
}

return arrayCopy.slice(min);
deprecated({
deprecated: 'faker.random.arrayElements()',
proposed: 'faker.helpers.arrayElements()',
since: 'v6.3.0',
until: 'v7.0.0',
});
return this.faker.helpers.arrayElements(array, count);
}

/**
Expand Down
53 changes: 51 additions & 2 deletions test/helpers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,9 +497,58 @@ describe('helpers', () => {
faker.seedValue
)}`, () => {
for (let i = 1; i <= NON_SEEDED_BASED_RUN; i++) {
describe('randomize()', () => {
// Will be marked as deprecated soon
describe('arrayElement', () => {
it('should return a random element in the array', () => {
const testArray = ['hello', 'to', 'you', 'my', 'friend'];
const actual = faker.helpers.arrayElement(testArray);

expect(testArray).toContain(actual);
});

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

expect(actual).toBe('hello');
});
});

describe('arrayElements', () => {
it('should return a subset with random elements in the array', () => {
const testArray = ['hello', 'to', 'you', 'my', 'friend'];
const subset = faker.helpers.arrayElements(testArray);

// Check length
expect(subset.length).toBeGreaterThanOrEqual(1);
expect(subset.length).toBeLessThanOrEqual(testArray.length);

// Check elements
subset.forEach((element) => {
expect(testArray).toContain(element);
});

// Check uniqueness
expect(subset).toHaveLength(new Set(subset).size);
});

it('should return a subset of fixed length with random elements in the array', () => {
const testArray = ['hello', 'to', 'you', 'my', 'friend'];
const subset = faker.helpers.arrayElements(testArray, 3);

// Check length
expect(subset).toHaveLength(3);

// Check elements
subset.forEach((element) => {
expect(testArray).toContain(element);
});

// Check uniqueness
expect(subset).toHaveLength(new Set(subset).size);
});
});

describe('randomize()', () => {
it('returns a random element from an array', () => {
const arr = ['a', 'b', 'c'];
const elem = faker.helpers.randomize(arr);
Expand Down