JSFiddle - React, Tailwind, and code Playground

by mschock

JavaScript

// input: [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
// output: [(0, 1), (3, 8), (9, 12)]
// What if we sorted our list of meetings by start time?

var input = [
    [0, 1],
    [3, 5],
    [4, 8],
    [10, 12],
    [9, 10]
],
    output = [];

function sort(input) {
    return [
    [0, 1], [3, 5], [4, 8], [9, 10], [10, 12]];
}

function condense_meeting_times(input) {
    input = sort(input);
    for (var i = 0; i < input.length; i++) {
        var elemNew = input[i],
            leftNew = elemNew[0],
            rightNew = elemNew[1];

        if (output.length === 0 || leftNew > output[output.length - 1][1]) {
            output.push([leftNew, rightNew]);
        } else {
            var elemLatest = output[output.length - 1],
                leftLatest = elemLatest[0],
                rightLatest = elemLatest[1];
            
            if (rightNew > rightLatest) {
            	elemLatest[1] = rightNew;   
            }
        }
    }
}

condense_meeting_times(input);

console.log('output1: ', output);

output = [];
input = [
    [1, 2],
    [2, 3]
];
condense_meeting_times(input);
console.log('output2: ', output);

output = [];
input = [
    [1, 5],
    [2, 3]
];
condense_meeting_times(input);
console.log('output3: ', output);

output = [];
input = [
    [1, 10],
    [2, 6],
    [3, 5],
    [7, 9]
];
condense_meeting_times(input);
console.log('output4: ', output);