Skip to content

Commit

Permalink
feat(utilities): add pickRandom (#486)
Browse files Browse the repository at this point in the history
Co-authored-by: Jeroen Claassens <support@favware.tech>
  • Loading branch information
Lioness100 and favna committed Oct 8, 2022
1 parent a4acb69 commit 20823c9
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
5 changes: 5 additions & 0 deletions packages/utilities/package.json
Expand Up @@ -226,6 +226,11 @@
"import": "./dist/lib/partition.mjs",
"require": "./dist/lib/partition.js"
},
"./pickRandom": {
"types": "./dist/lib/pickRandom.d.ts",
"import": "./dist/lib/pickRandom.mjs",
"require": "./dist/lib/pickRandom.js"
},
"./range": {
"types": "./dist/lib/range.d.ts",
"import": "./dist/lib/range.mjs",
Expand Down
1 change: 1 addition & 0 deletions packages/utilities/src/index.ts
Expand Up @@ -31,6 +31,7 @@ export * from './lib/objectKeys';
export * from './lib/objectToTuples';
export * from './lib/objectValues';
export * from './lib/partition';
export * from './lib/pickRandom';
export * from './lib/range';
export * from './lib/regExpEsc';
export * from './lib/roundNumber';
Expand Down
20 changes: 20 additions & 0 deletions packages/utilities/src/lib/pickRandom.ts
@@ -0,0 +1,20 @@
/**
* Picks a random element from an array
* @param array The array to pick a random element from
* @param amount Amount of values to obtain randomly (default: 1)
*/
export function pickRandom<T>(array: readonly T[], amount?: 1): T;
export function pickRandom<T>(array: readonly T[], amount: number): T[];
export function pickRandom<T>(array: readonly T[], amount = 1): T | T[] {
const arr = [...array];

if (typeof amount === 'undefined' || amount === 1) {
return arr[Math.floor(Math.random() * arr.length)];
}

if (!arr.length || !amount) {
return [];
}

return Array.from({ length: Math.min(amount, arr.length) }, () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]);
}
21 changes: 21 additions & 0 deletions packages/utilities/tests/pickRandom.test.ts
@@ -0,0 +1,21 @@
import { pickRandom } from '../src';

describe('pickRandom', () => {
test('GIVEN array THEN picks one random element', () => {
const array = ['a', 'b', 'c'];
expect(array).toContain(pickRandom(array));
});

test('GIVEN count of one THEN picks one random element', () => {
const array = ['a', 'b', 'c'];
expect(array).toContain(pickRandom(array, 1));
});

test('GIVEN count of two THEN picks two random elements', () => {
const array = ['a', 'b', 'c'];
const picked = pickRandom(array, 2);

expect(picked).toHaveLength(2);
expect(array).toEqual(expect.arrayContaining(picked));
});
});

0 comments on commit 20823c9

Please sign in to comment.