« get me outta code hell

S to shuffle queue - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/general-util.js
diff options
context:
space:
mode:
authorFlorrie <towerofnix@gmail.com>2018-06-04 23:25:36 -0300
committerFlorrie <towerofnix@gmail.com>2018-06-04 23:26:09 -0300
commit37aac405d924bd017a4d504c5a222eed3dae8884 (patch)
treeb7a95f82728b49ae112b32cbc3ca0ad128affbf9 /general-util.js
parent6055638558a345904b41467839191a7143862d25 (diff)
S to shuffle queue
Diffstat (limited to 'general-util.js')
-rw-r--r--general-util.js24
1 files changed, 24 insertions, 0 deletions
diff --git a/general-util.js b/general-util.js
index 879219d..2ce7ed4 100644
--- a/general-util.js
+++ b/general-util.js
@@ -63,3 +63,27 @@ module.exports.downloadPlaylistFromOptionValue = function(arg) {
     return downloadPlaylistFromLocalPath(arg)
   }
 }
+
+module.exports.shuffleArray = function(array) {
+  // 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/
+
+  const workingArray = array.slice(0)
+
+  let m = array.length
+
+  while (m) {
+    let i = Math.floor(Math.random() * m)
+    m--
+
+    // Stupid lol; avoids the need of a temporary variable!
+    Object.assign(workingArray, {
+      [m]: workingArray[i],
+      [i]: workingArray[m]
+    })
+  }
+
+  return workingArray
+}
+