Objects for Schedule

This shows how to use object notation and object functions to maintain a sorted class schedule.

by Ken Wai Ooi

HTML

<div id="results"></div>

JavaScript

// Array with strings for days of the week
var days=[
       "Monday",
       "Tuesday",
       "Wednesday",
       "Thursday",
       "Friday",
       "Saturday",
       "Sunday"
       ];

// Convert a string from "HH:MM" to
// minutes since the beginning of the day
function timeInMinutes(tm) {
    var separator = tm.indexOf(":");
    var last = tm.length;
    var hours = tm.slice(0, separator);
    var min = tm.slice(separator+1, last);
    min = Number(hours) * 60 + Number(min);
    return min;
}

function dayNumber(dayOfWeek) {
    return Number(days.indexOf(dayOfWeek));
}

//  Create a unit object
Unit = function (name, dow, time, duration) {
   this.name = name;          // name of unit
   this.dow  = dow;           // day of week
   this.time = time;          // time as "HH:MM"
   this.duration = duration;  // duration in hours

   // Return the start time in minutes since 
   // the beginning of the week
   this.tsow = function () {
     var day = dayNumber(dow);       // day number in week
     var tsod = timeInMinutes(time); // Time since start of day in minutes
     return tsod + day * 24*60;      // Return the time in minutes
   } 

   // Return details for this unit in HTML
   this.html = function () {
       var HTML = "";
       HTML += "</p>";
       HTML += "<strong>Unit: </strong>" + this.name + "</br>";
       HTML += "<strong>Day:  </strong>" + this.dow + "</br>";
       HTML += "<strong>Time: </strong>" + this.time + "</br>";
       HTML += "<strong>Duration: </strong>" + this.duration + " hours</br>";
       return HTML;
   }

}

// Create an Object named schedule
var schedule = {
    givenName: "Brian",
    familyName: "von Konsky".toUpperCase(),
    units : [ ],
    
    // Method to add an item to the schedule
    add : function(theUnit){this.units.push(theUnit);},
    
    // Method to generate HTML for the schedule
    html : function(){ 
        
        // Sort the list of units by start time and day
        var sorted=...