Skip to content

Instantly share code, notes, and snippets.

@liyaodong
Created April 7, 2024 05:41
Show Gist options
  • Save liyaodong/4bac0165d88ad07ab455850c71f74b5d to your computer and use it in GitHub Desktop.
Save liyaodong/4bac0165d88ad07ab455850c71f74b5d to your computer and use it in GitHub Desktop.
Calculate duration
"use strict";
const calculateTime = (ranges) => {
const totalTime = ranges.reduce(
(acc, x) => {
const start = x[0];
const end = x[1];
let currentTotal = 0;
// Case E, No overlap
if (acc.start === 0 || start >= acc.end) {
acc.start = start;
acc.end = end;
currentTotal = end - start;
} else if (end > acc.end) {
// Case D, Partial overlap with start in the range
currentTotal = end - acc.end;
acc.end = end;
}
// Case C, Within the range
acc.total += currentTotal;
return acc;
},
{ total: 0, start: 0, end: 0 }
);
return totalTime;
};
const result = calculateTime([
[Date.now() - 500, Date.now() - 300],
[Date.now() - 400, Date.now() - 200],
[Date.now() - 100, Date.now() - 50],
[Date.now() - 100, Date.now() - 40],
]);
console.log("result expected to be 360, actual:", result.total);
const result1 = calculateTime([
[100, 200],
[300, 400],
[500, 600],
]);
console.log("Test Case 1 expected to be 300, actual:", result1.total);
const result2 = calculateTime([
[100, 300],
[150, 250],
[200, 300],
]);
console.log("Test Case 2 expected to be 200, actual:", result2.total);
const result3 = calculateTime([
[100, 200],
[150, 250],
[300, 400],
[350, 450],
]);
console.log("Test Case 3 expected to be 300, actual:", result3.total);
const result4 = calculateTime([
[100, 200],
[200, 300],
[300, 400],
]);
console.log("Test Case 4 expected to be 300, actual:", result4.total);
const result5 = calculateTime([[100, 200]]);
console.log("Test Case 5 expected to be 100, actual:", result5.total);
const result6 = calculateTime([
[100, 200],
[150, 300],
[250, 400],
]);
console.log("Test Case 6 expected to be 300, actual:", result6.total);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment