From 6f00a1303e7173383512584bc3787eb75ee006d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20Segersl=C3=A4tt?= Date: Fri, 22 Feb 2019 13:34:35 +0100 Subject: [PATCH] Added optional parameter to getRandomEntry --- src/array-utils.ts | 18 ++++++++++++++++-- test/array-utils.spec.ts | 7 +++++++ 2 files changed, 23 insertions(+), 2 deletions(-) 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', () => {