Get total seconds from overlapping timespans

by AsciiSmoke

JavaScript

var timeRangesRaw1 = ['0.08-1.56', '0.08-5.56', '0.08-9.56'];
var timeRangesRaw2 = ['0.08-1.13', '0.08-1.13', '16.74-18.16'];
var timeRangesRaw3 = ['0.08-1.13', '0.08-1.13', '6.74-18.16'];


function getSeconds(rawtimespans) {

    // Get raw timespans from strings
    var timespans = [];
    rawtimespans.forEach(t => {
        var _split = t.split('-');

        if (_split.length === 2) {
        		// Add to the timespans array
            timespans.push({ start: parseFloat(_split[0].trim()), end: parseFloat(_split[1].trim()) });
        }
        else {
            //duff
            console.log("duff", _split);
        }
    });


    // First sort by start times
    var sorted = timespans.sort(function (a, b) {
        return a.start < b.start;
    });

    // Then check if there's an overlap
    sorted.forEach((item, index, arr) => {
        var next = arr[index + 1];
        item.junk = false;
        
        if (next) {
            var overlap = item.start < next.end && next.start < item.end;

            if (overlap) {
                // If the two overlap, update the start of next, then mark currentItem as Junk (to be removed outside of foreach loop)
                next.start = item.start;
                item.junk = true;
            }
        }
    });

    // Remove any items marked as 'junk'
    var junkFiltered = sorted.filter(i => i.junk === false);

    // Add up seconds for any remaining items and return total
    totalSeconds = 0;
    junkFiltered.forEach((item, index, arr) => {
        totalSeconds += (item.end - item.start);
    });

    return totalSeconds;
}

document.writeln(getSeconds(timeRangesRaw1) +", ");
document.writeln(getSeconds(timeRangesRaw2) +", ");
document.writeln(getSeconds(timeRangesRaw3) +", ");