Skip to content
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

feat: 🔥 random pick from array #328

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Create massive amounts of fake data in the browser and NodeJS. Tree Shakeable &

</p>

✅ &nbsp;197 Functions
✅ &nbsp;198 Functions
✅ &nbsp;Tree Shakable
✅ &nbsp;Fully Typed
✅ &nbsp;Factory Functions
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ title: Getting Started
/>
</p>

✅ &nbsp;197 Functions
✅ &nbsp;198 Functions
✅ &nbsp;Tree Shakable
✅ &nbsp;Fully Typed
✅ &nbsp;Entity Functions
Expand Down
1 change: 1 addition & 0 deletions packages/falso/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,4 @@ export {
} from './lib/factories/incremental-date';
export { randAggregation } from './lib/aggregation';
export { toCollection } from './lib/collection';
export { randPick } from './lib/pick';
38 changes: 38 additions & 0 deletions packages/falso/src/lib/pick.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { FakeOptions, fake } from './core/core';
import { randNumber } from './number';

/**
* Generate a random pick from an array.
*
* @category General
*
* @example
*
* randPick([ "A", "B", "C", ... ])
*
* @example
*
* randPick([ 1, 2, 3, ... ])
*
* @example
*
* randPick([ "test", 123, { hello:"world" }, ... ])
*
* @example
*
* randPick([ 1, 3, 8, 12],{ length: 10 })
*
*/
export function randPick<Options extends FakeOptions = never>(
array: Array<unknown>,
options?: Options
) {
if (!array || array.length === 0) {
throw new Error('the array need to have at least 1 element');
}

const factory = () => {
return array[randNumber({ min: 0, max: array.length - 1 })];
};
return fake(factory, options);
}
11 changes: 11 additions & 0 deletions packages/falso/src/tests/pick.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { randPick } from '../lib/pick';

describe('randPick', () => {
it('should throw an error on empty array', () => {
const test = () => {
randPick([]);
};
expect(test).toThrow(Error);
expect(test).toThrow('the array need to have at least 1 element');
});
});