diff --git a/src/array-utils.ts b/src/array-utils.ts index 96a0ae5..faf3625 100644 --- a/src/array-utils.ts +++ b/src/array-utils.ts @@ -22,9 +22,23 @@ export function flattenTree(array: T[] = [], key: string | ((s: T) = * Based on Math.random() * @param array The array of which you want a random entry */ -export function getRandomEntry(array: T[]): T { +export function getRandomEntry(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; } /** diff --git a/test/array-utils.spec.ts b/test/array-utils.spec.ts index beae446..e57e3f4 100644 --- a/test/array-utils.spec.ts +++ b/test/array-utils.spec.ts @@ -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', () => {