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
function insertValue(array, index, value) { | |
const newArray = [...array]; | |
newArray.splice(index, 0, value); | |
return newArray; | |
} | |
function replaceValue(array, start, end, value) { | |
const newArray = [...array]; | |
newArray.splice(start, 1 + (end - start), value); | |
return newArray; | |
} | |
/** | |
* @param {number[][]} intervals | |
* @param {number[]} newInterval | |
* @return {number[][]} | |
*/ | |
var insert = function(intervals, newInterval) { | |
if (intervals.length === 0) { | |
return [newInterval]; | |
} | |
let start; | |
let end; | |
for (let i = 0; i < intervals.length; i++) { | |
const current = intervals[i]; | |
const next = intervals[i + 1]; | |
if (start === undefined) { | |
const afterCurrentRangeButNotOverlapping = newInterval[0] > current[1] && (!next || newInterval[1] < next[0]); | |
if (afterCurrentRangeButNotOverlapping) { | |
return insertValue(intervals, i + 1, newInterval); | |
} | |
const beforeCurrentRangeButNotOverlapping = newInterval[0] < current[0] && newInterval[1] < current[0]; | |
if (beforeCurrentRangeButNotOverlapping) { | |
return insertValue(intervals, i, newInterval); | |
} | |
const startsInsideCurrentRange = newInterval[0] >= current[0] && newInterval[0] <= current[1]; | |
const startsBeforeCurrentRangeButContinuesInside = newInterval[0] <= current[0] && newInterval[1] >= current[0]; | |
const overlappingCurrentRange = startsInsideCurrentRange || startsBeforeCurrentRangeButContinuesInside; | |
if (overlappingCurrentRange) { | |
start = i; | |
end = i; | |
continue; | |
} | |
} else { | |
const endsInsideOrAfterCurrentRange = newInterval[1] >= current[0]; | |
if (endsInsideOrAfterCurrentRange) { | |
end = i; | |
continue; | |
} | |
} | |
} | |
const lengthenedInterval = [ | |
Math.min(newInterval[0], intervals[start][0]), | |
Math.max(newInterval[1], intervals[end][1]) | |
]; | |
return replaceValue(intervals, start, end, lengthenedInterval); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment