I wanted to get some eyes on some code that I wrote, and see if anyone can help improve what I did. Just looking for some constructive feedback to help make my code more performant, and more elegant.
From a high level my code needs to accomplish the following:
Create a function that takes an array of objects that each represent an event. Each object in the array has a start and end time represented in minutes. The start and end times are represented as minutes after 9am. For example {start:30, end: 60} represents an event that starts at 9:30am and ends at 10am. The function takes the objects, and plots them as events on a vertical timeline. Events that have crossover will split the container in half, while events that don’t crossover will take the whole container width.
Here is the JS that I wrote to accomplish the above task:
//sample data - array of objects that represent events
var myArray = [
{start: 30, end: 130},
{start: 140, end: 147},
{start: 145, end: 155},
{start: 150, end: 175},
{start: 200, end: 250},
];
var myFunc = function(a) {
//sort the input array from earliest start time to latest. Items with identical start times will compare end times - the longer duration item resolves with lower index. Assumes no exact duplicate items.
var sortedDates = a.sort(function(a,b) {
var caseOne= (a.end>b.end) ? -1 : 1,
caseTwo= a.start - b.start;
return (a.start===b.start) ? caseOne : caseTwo;
});
for(var i=0; i<sortedDates.length; i++) {
var currentItem = sortedDates[i],
itemDuration = currentItem.end-currentItem.start,
itemTop = currentItem.start,
prevItem = sortedDates[i-1],
nextItem = sortedDates[i+1],
newDiv = document.createElement('div');
//set a default direction to each item
currentItem.direction = 'left';
//determine which items overlap and set a property to indicate
if(nextItem !== undefined && (currentItem.end - nextItem.start > 0)) {
currentItem.overlap = true;
nextItem.overlap = true;
}
//ensure items flow in UI by staggering overlapping items
if(prevItem !== undefined && (prevItem.direction === 'left')) {
currentItem.direction = 'right';
}
//set class names on new DOM element based on overlap
if(currentItem.overlap === true) {
if(currentItem.hasOwnProperty('direction')) {
newDiv.setAttribute('class', 'split '+currentItem.direction);
}
else {
newDiv.setAttribute('class', 'split');
}
}
//set the size and position based on computed duration and start time
newDiv.setAttribute('style', 'height:'+itemDuration+'px; top:'+itemTop+'px');
//insert new element into DOM
document.getElementById('stuff').appendChild(newDiv);
}
};
Here is a rough working example.