The above if can be simplified. mergeEndTime and mergeSumofdurations can trivially be pulled out. merge.push(item) can be pulled out if the base state is that at the start of a merge we have merge = []. The only difference should be mergeStartTime.