Created
May 25, 2024 13:54
-
-
Save gruhh/4b16e6b0599dd35ee3a66fecfe065d11 to your computer and use it in GitHub Desktop.
Function to shuffle the values of an array (Use case: simulating dice rolls for games without an RNG)
This file contains 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
/** | |
* Shuffles an array and optionally returns a specified number of elements from the shuffled array. | |
* | |
* @param {Array} arr - The array to be shuffled. | |
* @param {number} [size=0] - The number of elements to return from the shuffled array. | |
* If 0, the entire shuffled array is returned. Defaults to 0. | |
* @returns {Array} A new array containing the shuffled elements. If `size` is specified, | |
* the array will contain only the first `size` elements of the shuffled array. | |
* | |
* @example | |
* // Shuffles the array and returns all elements in random order | |
* let shuffledArray = shuffle([1, 2, 3, 4, 5]); | |
* console.log(shuffledArray); // e.g., [3, 1, 4, 5, 2] | |
* | |
* @example | |
* // Shuffles the array and returns only 3 elements from the shuffled array | |
* let partialShuffledArray = shuffle([1, 2, 3, 4, 5], 3); | |
* console.log(partialShuffledArray); // e.g., [4, 2, 5] | |
*/ | |
function shuffle(arr, size = 0) { | |
let newArray = []; | |
do { | |
// get a random position of the arr | |
let random = Math.floor(Math.random() * arr.length); | |
//add the value of that position to the new array | |
newArray.push(arr[random]); | |
// remove the position of the arr | |
arr = arr.filter((v, k) => k !== random); | |
} while (arr.length > 0); | |
if (size > 0) { | |
newArray = newArray.slice(0, size); | |
} | |
return newArray; | |
} | |
// Example of random order of a D6 | |
let d6Array = Array.from({ length: 6 }, (value, index) => index + 1); | |
console.log(shuffle(d6Array)); | |
// Example of a D20 roll | |
let d20Array = Array.from({ length: 20 }, (value, index) => index + 1); | |
console.log(shuffle(d20Array, 1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment