From 2635f089b0ce5e37df538b68ca6263439bf91b40 Mon Sep 17 00:00:00 2001 From: "(quasar) nebula" Date: Tue, 14 May 2024 13:36:05 -0300 Subject: add limit option to shuffleArray --- general-util.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/general-util.js b/general-util.js index bb0574a..b767a1b 100644 --- a/general-util.js +++ b/general-util.js @@ -78,7 +78,7 @@ export function downloadPlaylistFromOptionValue(arg) { } } -export function shuffleArray(array) { +export function shuffleArray(array, limit = array.length) { // Shuffles the items in an array. Returns a new array (does not modify the // passed array). Super-interesting post on how this algorithm works: // https://bost.ocks.org/mike/shuffle/ @@ -86,10 +86,12 @@ export function shuffleArray(array) { const workingArray = array.slice(0) let m = array.length + let n = limit - while (m) { + while (n) { let i = Math.floor(Math.random() * m) m-- + n-- // Stupid lol; avoids the need of a temporary variable! Object.assign(workingArray, { @@ -98,7 +100,11 @@ export function shuffleArray(array) { }) } - return workingArray + if (limit === array.length) { + return workingArray + } else { + return workingArray.slice(0, limit) + } } export function throttlePromise(maximumAtOneTime = 10) { -- cgit 1.3.0-6-gf8a5