aboutsummaryrefslogtreecommitdiff
path: root/src/modules
diff options
context:
space:
mode:
authorEric Cheng <[email protected]>2023-01-26 11:09:47 -0500
committerGitHub <[email protected]>2023-01-26 16:09:47 +0000
commitb86638d478fa21fafa9aaa3e247a08b479bf5a9d (patch)
treecd897a089b3b27e75158e758c38bebba97a0a8a8 /src/modules
parentc7ce35a47d336de3ac6f73efd7390ba696b6a4b2 (diff)
downloadfaker-b86638d478fa21fafa9aaa3e247a08b479bf5a9d.tar.xz
faker-b86638d478fa21fafa9aaa3e247a08b479bf5a9d.zip
feat(helpers): add length range support in `arrayElements` (#1772)
Diffstat (limited to 'src/modules')
-rw-r--r--src/modules/helpers/index.ts39
1 files changed, 27 insertions, 12 deletions
diff --git a/src/modules/helpers/index.ts b/src/modules/helpers/index.ts
index 8492a096..a4ecdf71 100644
--- a/src/modules/helpers/index.ts
+++ b/src/modules/helpers/index.ts
@@ -561,13 +561,14 @@ export class HelpersModule {
*
* @template T The type of the entries to pick from.
* @param array Array to pick the value from.
- * @param count Number of elements to pick.
+ * @param count Number or range 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]
+ * faker.helpers.arrayElements([1, 2, 3, 4, 5], { min: 2, max: 4 }) // [3, 5, 1]
*
* @since 6.3.0
*/
@@ -575,22 +576,36 @@ export class HelpersModule {
// TODO @Shinigami92 2022-04-30: We want to remove this default value, but currently it's not possible because some definitions could be empty
// See https://github.com/faker-js/faker/issues/893
array: ReadonlyArray<T> = ['a', 'b', 'c'] as unknown as ReadonlyArray<T>,
- count?: number
+ count?:
+ | number
+ | {
+ /**
+ * The minimum number of elements to pick.
+ */
+ min: number;
+ /**
+ * The maximum number of elements to pick.
+ */
+ max: number;
+ }
): T[] {
- if (typeof count !== 'number') {
- count =
- array.length === 0
- ? 0
- : this.faker.number.int({ min: 1, max: array.length });
- } else if (count > array.length) {
- count = array.length;
- } else if (count < 0) {
- count = 0;
+ if (array.length === 0) {
+ return [];
+ }
+
+ const numElements = this.rangeToNumber(
+ count ?? { min: 1, max: array.length }
+ );
+
+ if (numElements >= array.length) {
+ return this.shuffle(array);
+ } else if (numElements <= 0) {
+ return [];
}
const arrayCopy = array.slice(0);
let i = array.length;
- const min = i - count;
+ const min = i - numElements;
let temp: T;
let index: number;