Skip to content

Commit

Permalink
fix(ui): Sort playlist feature bug (#415)
Browse files Browse the repository at this point in the history
Closes #411

## What does this PR do / solve?

Currently the sort playlist feature is using the index and paylistname data attributes to sort by date and alphabet. The issue is that I did not realize that the array sort function takes into consideration lower and upper case when sorting.

Also the index is being sorted as a string rather than a number which causes the playlist to be in the incorrect order when sorting by date.

## Overview of changes

The sort function will now lower case all playlist titles and convert index strings into numbers before sorting to prevent these bugs.
  • Loading branch information
compiuta committed Nov 30, 2020
1 parent 5f08d4f commit aec724d
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions public/js/whyd.js
Original file line number Diff line number Diff line change
Expand Up @@ -1328,16 +1328,21 @@ window.sortPlaylists = function (sortType) {
const allPlaylists = playlistsContainer.querySelectorAll('.playlist');
let playlistsFragment = document.createDocumentFragment();
let allPlaylistsObject = {};
let sortedPlaylistObjectKeys = [];

if (allPlaylists.length > 2) {
allPlaylists.forEach((playlist, index) => {
if (playlist.dataset.playlistname) {
//store playlist name in a variable and add index to create a unique key in allPlaylistsObject
const playlistNameKey =
playlist.dataset.playlistname.toLowerCase() + index;

if (!playlist.dataset.index) {
playlist.setAttribute('data-index', index);
}

if (sortType === 'alphabetize') {
allPlaylistsObject[playlist.dataset.playlistname] = playlist;
allPlaylistsObject[playlistNameKey] = playlist;
} else if (sortType === 'date') {
allPlaylistsObject[playlist.dataset.index] = playlist;
}
Expand All @@ -1348,11 +1353,20 @@ window.sortPlaylists = function (sortType) {

playlistsContainer.innerHTML = '';

Object.keys(allPlaylistsObject)
.sort()
.forEach((playlist) =>
playlistsFragment.appendChild(allPlaylistsObject[playlist])
if (sortType === 'date') {
sortedPlaylistObjectKeys = Object.keys(allPlaylistsObject).sort(
//if sorting by date first convert index key string to a number with '+' then compare to sort in ascending order.
function (firstPlaylistIndex, secondPlaylistIndex) {
return +firstPlaylistIndex - +secondPlaylistIndex;
}
);
} else {
sortedPlaylistObjectKeys = Object.keys(allPlaylistsObject).sort();
}

sortedPlaylistObjectKeys.forEach((playlist) =>
playlistsFragment.appendChild(allPlaylistsObject[playlist])
);

playlistsContainer.appendChild(playlistsFragment);
}
Expand Down

0 comments on commit aec724d

Please sign in to comment.