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.
npm run import -- "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;
/**
* 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:
sumEvents(events)
function:
summary
, start
, and end
.Initialization:
total
variable to 0 to store the cumulative duration.Iterating through Events:
forEach
to loop through each event in the events
array.Handling Missing End Times:
end
property exists and if it has a dateTime
property. If either is missing, it logs a message and skips the event.Calculating Duration:
start
and end
times are present:
Date
objects from the start.dateTime
and end.dateTime
strings.total
.isNaN(total)
to handle potential errors and throw an error if the calculation results in NaN.Returning Total Duration:
total
milliseconds by 1000 (to get seconds), then by 60 (to get minutes).Export:
sumEvents
function for use in other parts of the project.Let me know if you have any other code snippets you'd like me to explain!