Skip to content

Commit

Permalink
Added optional parameter to getRandomEntry
Browse files Browse the repository at this point in the history
  • Loading branch information
JakobSegerslatt committed Feb 22, 2019
1 parent b861537 commit 6f00a13
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/array-utils.ts
Expand Up @@ -22,9 +22,23 @@ export function flattenTree<T = object>(array: T[] = [], key: string | ((s: T) =
* Based on Math.random()
* @param array The array of which you want a random entry
*/
export function getRandomEntry<T>(array: T[]): T {
export function getRandomEntry<T>(array: T[], arrayToPopulate?: T[], tryCount?: number): T {
const randomIndex = Math.floor(Math.random() * array.length);
return array[randomIndex];
const randomEntry = array[randomIndex];

/**
* If arrayToPopulate is provided; run this method again.
* Repeat until the maxium amount of tries has been done
* so we avoid getting stuck in an infinite loop
* (which could happen if @param array only has a single entry)
*/
tryCount = tryCount || 5;
if (tryCount > 0 && arrayToPopulate && arrayToPopulate.includes(randomEntry)) {
tryCount--;
return getRandomEntry(array, arrayToPopulate);
}

return randomEntry;
}

/**
Expand Down
7 changes: 7 additions & 0 deletions test/array-utils.spec.ts
Expand Up @@ -89,6 +89,13 @@ describe('getRandomEntry() test', () => {
const bar = getRandomEntry([]);
expect(bar).to.equal(undefined);
});

it('should return the first entry for an array of 1', () => {
const source = [{ foo: 'foo' }];
const arrayToPopulate = [{ foo: 'foo' }];
const bar = getRandomEntry(source, arrayToPopulate);
expect(bar).to.eql({ foo: 'foo' });
});
});

describe('groupArrayByProperty() test', () => {
Expand Down

0 comments on commit 6f00a13

Please sign in to comment.