Created
August 7, 2023 17:16
-
-
Save lyatziv/09cbf5f3f0acc5e27dc8b757622e4932 to your computer and use it in GitHub Desktop.
javascript random entries from an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getRandomPercentageElements = (array, percentage) => { | |
if (!Array.isArray(array) || array.length === 0 || typeof percentage !== 'number' || percentage < 0 || percentage > 100) { | |
throw new Error('Invalid input'); | |
} | |
const numberOfElements = Math.ceil(array.length * (percentage / 100)); | |
return getRandomEntriesFromArray(array, numberOfElements); | |
} | |
const getRandomEntriesFromArray = (array, numberOfElements) => { | |
if (!Array.isArray(array) || array.length === 0 || typeof numberOfElements !== 'number' || numberOfElements < 0 || numberOfElements > array.length) { | |
throw new Error('Invalid input'); | |
} | |
const result = []; | |
const selectedIndexes = new Set(); | |
while (selectedIndexes.size < numberOfElements) { | |
const randomIndex = Math.floor(Math.random() * array.length); | |
if (!selectedIndexes.has(randomIndex)) { | |
selectedIndexes.add(randomIndex); | |
result.push(array[randomIndex]); | |
} | |
} | |
return result; | |
} | |
// if quantity is less that 1 use percent | |
// otherwise use a number | |
const randomFromArray(array, quantity) => { | |
if (!Array.isArray(array) || array.length === 0 || typeof quantity !== 'number') { | |
throw new Error('Invalid input'); | |
} | |
if (quantity < 1) { | |
return getRandomPercentageElements(array, quantity * 100) | |
} | |
return getRandomEntriesFromArray(array, quantity); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment