title: Find nearest free slot in a time array
body: <p>I'm working on a queue system for a clinic. The person at the front desk has two options to add patients to the queue.</p>
  
  <ol>
  <li>Patients with fixed appointments</li>
  <li>Walk-in patients</li>
  </ol>
  
  <p>So for example there are four patients already in the queue, my existing appointments array looks like</p>
  
  <pre><code>existing_appointments = ["09:30", "10:00", "12:15", "13:45"];
  </code></pre>
  
  <p>And average checkup time for a patient is 15 minutes.</p>
  
  <pre><code>avg_wait_per_patient = 15;
  </code></pre>
  
  <p>As soon a patient walk's in, I'm finding best available time slot for him.</p>
  
  <p>Say the time right now is 09:00</p>
  
  <pre><code>current_time = "09:00";
  </code></pre>
  
  <p>The below function <code>find_free_slot()</code> does not work because it returns 09:15 instead of 09:00 as there is no appointment on this slot.</p>
  
  <p>What I aim to achieve is, if there is no one near <code>current_time + avg_wait_per_patient</code>, the person should be given <code>current_time</code> slot. If this slot if not available it should loop though the array unless it finds a free one. And if it fails the person should be added to the time on <code>last_index_of_array + avg_wait</code>.</p>
  
  <pre><code>function toMinutes(t) {
      return 60 * Number(t.split(":")[0]) + Number(t.split(":")[1]);
  }
  function reverse_toMinutes(t) {
      return ("0" + Math.floor(t / 60)).slice(-2) + ":" + ("0" + t % 60).slice(-2);
  }
  function find_free_slot(ct,appointments,avg_wait) {
      ct = toMinutes(ct);
      free_slot = '';
      if(appointments.length==0) {
          free_slot = ct;
      } else {
          for(i=0; i&lt;appointments.length; i++) {
              appointment = toMinutes(appointments[i]);
              if(free_slot &lt;= appointment - avg_wait) {
                  i == 0 ?
                      free_slot = ct + avg_wait :
                      free_slot = toMinutes(appointments[i - 1]) + avg_wait;
                  break;
              }
          }   
      }
      return reverse_toMinutes(free_slot);
  }
  </code></pre>
  
  <p><a href="https://jsfiddle.net/2r4xm69k/" rel="nofollow noreferrer">jsfiddle</a></p>