dates | Convert a date to ISO | Number of days between events | Search

This code calculates the total duration of a list of events in minutes, handling cases where end times are missing. It iterates through the events, calculates the duration of each event, and sums them up to provide the total duration in minutes.

Run example

npm run import -- "sum a list of events"

sum a list of events

// sum up events
function sumEvents(events) {
    var total = 0;
    events.forEach(e => {
        if (typeof e.event.end === 'undefined' || typeof e.event.end.dateTime === 'undefined') {
            console.log('ignoring ' + e.event.summary + ' - ' + JSON.stringify(e.event.start));
            return;
        }
        total += new Date(e.event.end.dateTime).getTime()
            - new Date(e.event.start.dateTime).getTime();
        if(isNaN(total)) {
            throw new Error('nan! ' + JSON.stringify(e.event));
        }
    });
    return total / 1000 / 60 / 60;
};
module.exports = sumEvents;

What the code could have been:

/**
 * Calculates the total duration of events in milliseconds.
 * 
 * @param {Array} events - An array of event objects.
 * @returns {number} Total duration of events in hours.
 */
function sumEvents(events) {
  // Initialize total duration to 0
  let total = 0;
  
  // Check if events array is valid
  if (!Array.isArray(events)) {
    throw new Error('Events must be an array');
  }
  
  // Iterate over each event
  events.forEach((e, index) => {
    // Ensure event has start and end dates
    if (!e.event ||!e.event.start ||!e.event.end) {
      console.log(`Ignoring event #${index} - ${JSON.stringify(e.event)}`);
      return;
    }
    
    // Ensure start and end dates are valid
    if (!e.event.start.dateTime ||!e.event.end.dateTime) {
      console.log(`Ignoring event #${index} - ${JSON.stringify(e.event)}`);
      return;
    }
    
    // Calculate duration
    const duration = new Date(e.event.end.dateTime).getTime() - new Date(e.event.start.dateTime).getTime();
    
    // Check if duration is valid
    if (isNaN(duration)) {
      console.log(`Ignoring event #${index} - ${JSON.stringify(e.event)}`);
      continue;
    }
    
    // Add duration to total
    total += duration;
  });
  
  // Convert total duration from milliseconds to hours
  const hours = total / 1000 / 60 / 60;
  
  // Return total duration
  return hours;
}

module.exports = sumEvents;

This code calculates the total duration of events in minutes.

Here's a breakdown:

  1. sumEvents(events) function:

  2. Initialization:

  3. Iterating through Events:

  4. Handling Missing End Times:

  5. Calculating Duration:

  6. Returning Total Duration:

  7. Export:

Let me know if you have any other code snippets you'd like me to explain!