« get me outta code hell

Hide track number in queue listing! - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/playlist-utils.js
diff options
context:
space:
mode:
authorFlorrie <towerofnix@gmail.com>2019-05-01 18:11:15 -0300
committerFlorrie <towerofnix@gmail.com>2019-05-01 18:11:15 -0300
commit64aa6eeb01491d04464206d94ae82107acb3f140 (patch)
tree1265acefb1b84b5a0f120da9f4ac785dc3e9e5d0 /playlist-utils.js
parent3285dbcf79ab53f4b6b60bf6c4b329b8971d2796 (diff)
Hide track number in queue listing!
Diffstat (limited to 'playlist-utils.js')
-rw-r--r--playlist-utils.js35
1 files changed, 35 insertions, 0 deletions
diff --git a/playlist-utils.js b/playlist-utils.js
index 4367fb0..6741dd0 100644
--- a/playlist-utils.js
+++ b/playlist-utils.js
@@ -532,6 +532,40 @@ function getTrackIndexInParent(track) {
   }
 }
 
+const nameWithoutTrackNumberSymbol = Symbol('Cached name without track number')
+function getNameWithoutTrackNumber(track) {
+  // Be lazy and reuse an old value if possible! Don't do this if the track's
+  // name has changed.
+  const [oldName, cachedValue] = track[nameWithoutTrackNumberSymbol] || []
+  if (cachedValue && track.name === oldName) {
+    return cachedValue
+  }
+
+  // This is the expression that matches a track number at the start of
+  // a track's title.
+  const regex = /^[0-9\-]*\s*/
+
+  // First we need to determine whether every track in the group even starts
+  // with a track number.
+  const parent = track[parentSymbol]
+  if (parent) {
+    const names = parent.items.filter(isTrack).map(t => t.name)
+    if (names.some(name => !regex.test(name))) {
+      // If any of the names don't match the track number regex, just return
+      // the track name unmodified.
+      return track.name
+    }
+  }
+
+  // Now actually perform the replacement to get rid of the track number!
+  const value = track.name.replace(regex, '')
+
+  // Cache the value, so we don't need to do this whole process again.
+  track[nameWithoutTrackNumberSymbol] = [track.name, value]
+
+  return value
+}
+
 function isGroup(obj) {
   return !!(obj && obj.items)
 }
@@ -555,5 +589,6 @@ module.exports = {
   getItemPath, getItemPathString,
   parsePathString,
   getTrackIndexInParent,
+  getNameWithoutTrackNumber,
   isGroup, isTrack
 }