Skip to content

Instantly share code, notes, and snippets.

@victorstanciu
Created January 20, 2016 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorstanciu/b9ab0fdb024565d24f2a to your computer and use it in GitHub Desktop.
Save victorstanciu/b9ab0fdb024565d24f2a to your computer and use it in GitHub Desktop.
function getTimeslots(meetings) {
sortMeetings(meetings);
meetings = removeContained(meetings);
var timeslots = [], current, next;
for (var i = 0; i < meetings.length - 1; i++) {
current = meetings[i];
next = meetings[i + 1];
if (current[1] < next[0]) {
timeslots.push([current[1], next[0]]);
}
}
return timeslots;
}
function sortMeetings(meetings) {
meetings.sort(function (a, b) {
if (a[0] < b[0]) {
return -1;
} else if (a[0] > b[0]) {
return 1;
} else {
if (a[1] < b[1]) {
return -1;
} else {
return 1;
}
}
});
}
function removeContained(input) {
var meetings = [], current, previous;
if (input.length > 0) {
for (var i = input.length - 1; i > 0; i--) {
current = input[i];
previous = input[i - 1];
if (current[1] < previous[1]) {
continue;
}
meetings.unshift(current);
}
meetings.unshift(input[0]);
}
return meetings
}
var tests = {total: 0, passed: 0, failed: 0};
function check(meetings, expected) {
tests.total++;
var timeslots = getTimeslots(meetings);
if (timeslots.toString() == expected.toString()) {
tests.passed++;
} else {
tests.failed++;
console.error("Expected: " + JSON.stringify(expected) + ". Got: " + JSON.stringify(timeslots));
}
}
check(
[[0, 1], [3, 5], [4, 8], [10, 12], [4, 7], [9, 10]],
[[1, 3], [8, 9]]
);
check(
[[0, 1], [1, 12]],
[]
);
check(
[],
[]
);
check(
[[1, 3]],
[]
);
check(
[[3, 5], [2, 6], [7, 10]],
[[6, 7]]
);
console.log(tests);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment