« get me outta code hell

add limit option to shuffleArray - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2024-05-14 13:36:05 -0300
committer(quasar) nebula <qznebula@protonmail.com>2024-05-14 13:36:05 -0300
commit2635f089b0ce5e37df538b68ca6263439bf91b40 (patch)
tree5c10253614de3fb901a2adb1e2027d084b5e2e2a
parent27af62f38d2f0a99af5c34963d27197467fb0141 (diff)
add limit option to shuffleArray
-rw-r--r--general-util.js12
1 files 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) {