Skip to content

Commit b786440

Browse files
authored
Merge pull request #8729 from ever-co/fix/array-random-element
[Feat] Random Array Element Utils
2 parents 93c26a9 + d29e8f0 commit b786440

2 files changed

Lines changed: 16 additions & 1 deletion

File tree

packages/utils/src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
export * from './lib/ensure-http-prefix';
21
export * from './lib/array-sum';
2+
export * from './lib/array-random-element';
33
export * from './lib/average';
44
export * from './lib/build-query-string';
55
export * from './lib/camel-to-snake-case';
@@ -9,6 +9,7 @@ export * from './lib/convert-to-hex';
99
export * from './lib/deduplicate';
1010
export * from './lib/deep-clone';
1111
export * from './lib/deep-merge';
12+
export * from './lib/ensure-http-prefix';
1213
export * from './lib/generate-encryption-key';
1314
export * from './lib/generate-sha256-hash';
1415
export * from './lib/extract-name-from-email';
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* Returns a random element from an array.
3+
*
4+
* @param array - The array to select an element from.
5+
* @returns A random element from the array, or `null` if the array is empty.
6+
*/
7+
export function getRandomElement<T>(array: T[]): T | null {
8+
if (!Array.isArray(array) || array.length === 0) {
9+
return null; // Return null if the array is empty or not valid
10+
}
11+
12+
const randomIndex = Math.floor(Math.random() * array.length);
13+
return array[randomIndex];
14+
}

0 commit comments

Comments
 (0)