Created
September 9, 2021 16:08
-
-
Save diegoarcega/1742557f76e15f812dd83b68cce1c808 to your computer and use it in GitHub Desktop.
Sort groups in a list view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sorts therapy groups by name, therapist and topic and adds therapist data to the payload | |
const EMPTY_ARRAY = []; | |
export function processGroups(groups = EMPTY_ARRAY, therapists = EMPTY_ARRAY) { | |
const groupsLength = groups.length; | |
const therapistsLength = therapists.length; | |
const groupsWithTherapistData = []; | |
function defaultGroupSort(groups = []) { | |
return groups.sort((a, b) => { | |
const compareName = a.name.localeCompare(b.name); | |
const compareTherapist = a.therapist.first.localeCompare(b.therapist.first); | |
const compareTopic = a.topic.localeCompare(b.topic); | |
return compareName || compareTherapist || compareTopic; | |
}); | |
} | |
function groupByGroupSchedule(groups = []) { | |
const STRING_LENGTH_TO_COMPARE_IF_SAME_GROUP = 17; | |
return groups.reduce( | |
(acc, item) => { | |
const groupNameForComparison = item.name.slice(0, STRING_LENGTH_TO_COMPARE_IF_SAME_GROUP); | |
const hasOtherSchedule = groups | |
.filter(g => g.id !== item.id) | |
.some(g => g.name.includes(groupNameForComparison)); | |
if (hasOtherSchedule) { | |
acc[0] = [...acc[0], item]; | |
} else { | |
acc[1] = [...acc[1], item]; | |
} | |
return acc; | |
}, | |
[[], []], | |
); | |
} | |
for (let i = 0; i < groupsLength; i++) { | |
for (let j = 0; j < therapistsLength; j++) { | |
if (groups[i].therapist === therapists[j].username) { | |
groupsWithTherapistData.push({ | |
...groups[i], | |
therapist: therapists[j], // add therapist details to the group | |
hasStarted: hasGroupStarted(groups[i].starts), | |
}); | |
} | |
} | |
} | |
const [groupsWithMoreScheduleOptions, groupsSingleSchedule] = groupByGroupSchedule(groupsWithTherapistData); | |
return [...defaultGroupSort(groupsWithMoreScheduleOptions), ...defaultGroupSort(groupsSingleSchedule)]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment