Last active
April 21, 2017 16:53
-
-
Save blasten/706e2d9c37c5ff7b363a195a66599cee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SENTINEL = -Infinity; | |
function groupEvents(events) { | |
if (!Array.isArray(events) || events.length === 0) { | |
return []; | |
} | |
events = events.slice(); | |
events.sort((a, b) => a.start - b.start); | |
let group, | |
minColumnEnd = SENTINEL, | |
prevEnd = SENTINEL, | |
currentColumns = [SENTINEL]; | |
for (let i = 0, event; event = events[i]; i++) { | |
let candColumn = -1, columnClosed = 0; | |
if (minColumnEnd < event.start) { | |
for (let j = 0, columnEnd; columnEnd = currentColumns[j]; j++) { | |
if (columnEnd < event.start) { | |
columnEnd = j; | |
columnClosed++; | |
} | |
} | |
} | |
if (columnClosed === currentColumns.length) { | |
group = { columns: 1 }; | |
currentColumns = [SENTINEL]; | |
candColumn = 0; | |
} else if (candColumn === -1) { | |
currentColumns.push(SENTINEL); | |
candColumn = currentColumns.length - 1; | |
group.columns++; | |
} | |
currentColumns[candColumn] = event.end; | |
minColumnEnd = Math.min(minColumnEnd, currentColumns[candColumn]); | |
event.group = group; | |
event.column = candColumn; | |
} | |
return events; | |
} | |
// http://jsbin.com/qazixew/edit?js,output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment