Skip to content

Instantly share code, notes, and snippets.

@nramirez
Created January 18, 2015 20:26
Show Gist options
  • Save nramirez/4e3ad8369dde3ede282b to your computer and use it in GitHub Desktop.
Save nramirez/4e3ad8369dde3ede282b to your computer and use it in GitHub Desktop.
Sum of Intervals
function sumIntervals(intervals){
var uniArr = [intervals[0]], helper = true;
intervals.reduce(function(lastInt, actualInt){
uniArr.map(function(e){
if (!helper) {return};
//This validates if the array contains the klk[0]
if (actualInt[0] >= e[0] && actualInt[0] <= e[1]) {
if(e[1] < actualInt[1])
e[1] = actualInt[1];
helper = false;
} else if (actualInt[1] >= e[0] && actualInt[1] <= e[1]) {
//This validates if the array contains the klk[1]
if(e[0] < actualInt[0])
e[10] = actualInt[0];
helper = false;
};
return e;
},0);
if (helper) { uniArr.push(actualInt); };
helper= true;
});
//Sum all no overlapping array
var theSum = uniArr.reduce(function(last, actual){
return last + actual[1] - actual[0];
},0);
return theSum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment