DS&A: How to optimize a schedule so that empty slots are at the end of the day?

I’m writing a small program to schedule therapists and patients based on their availability. I’m able to generate an initial schedule, but am currently trying to optimize the therapists’ schedules so that, when possible, any empty slots are at the end of the day (and they can go home early!).

I’m not too worried about time or space complexity because the numbers in question are pretty small (there are always 8 slots in the day).

My idea is a recursive method that takes an empty slot and, starting with the appointments at the end of the day, checks if any sessions can be moved to that slot. Once an appointment has been moved into the empty slot, we take the new empty slot and call the method again with that. The success base case is that the given empty slot is at the end of the day, and the failure base case is that no appointments can be moved to the given empty slot.

Here is a slightly simplified version of my code. It’s currently getting stuck in a loop where it trades two appointments back and forth forever. I could keep trace of the index and make sure that an appointment never moves back to where it came from, but then I think I’d just run into a 3-appointment loop.

emptySlots.forEach((emptySlot) => {
  const swapAppts = (slotToFill): boolean => { 
     if (slotToFill === lastSlot) return true;

     for (let i = 1; i < apptsLastToFirst.length; i++) {
        let appointment = apptsLastToFirst[i];
        if (appointment.patient.isAvailable(slotToFill)) {
          const nextSlotToFill = appointment.time;
          appointment.time = slotToFill;
          apptsLastToFirst.sort((a, b) => b.time.localeCompare(a.time));
          return swapAppts(nextSlotToFill);
        }
     }
     return false;
  };
}

Does anyone know 1) how I could adjust this method to avoid loops or 2) a better way to go about solving this? Conceptually it feels like a directed graph problem, and I would imagine there’s already an existing algorithm to solve it, but I don’t know what it is.