Skip to content

Commit

Permalink
Fix bug in getOverlappingDaysInIntervals
Browse files Browse the repository at this point in the history
Fixed bug in `getOverlappingDaysInIntervals` caused by incorrect sorting of interval components that led to 0 for timestamps of different lengths.
  • Loading branch information
kossnocorp committed Jan 20, 2024
1 parent e0a272d commit ad2c654
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/getOverlappingDaysInIntervals/index.ts
Expand Up @@ -41,11 +41,11 @@ export function getOverlappingDaysInIntervals<DateType extends Date>(
const [leftStartTime, leftEndTime] = [
+toDate(intervalLeft.start),
+toDate(intervalLeft.end),
].sort();
].sort((a, b) => a - b);
const [rightStartTime, rightEndTime] = [
+toDate(intervalRight.start),
+toDate(intervalRight.end),
].sort();
].sort((a, b) => a - b);

const isOverlapping =
leftStartTime < rightEndTime && rightStartTime < leftEndTime;
Expand Down
16 changes: 15 additions & 1 deletion src/getOverlappingDaysInIntervals/test.ts
@@ -1,7 +1,7 @@
/* eslint-env mocha */

import assert from "assert";
import { describe, it } from "vitest";
import { describe, expect, it } from "vitest";
import { getOverlappingDaysInIntervals } from "./index.js";

describe("getOverlappingDaysInIntervals", () => {
Expand Down Expand Up @@ -214,4 +214,18 @@ describe("getOverlappingDaysInIntervals", () => {
assert(numOverlappingDays === 0);
});
});

it("properly sorts the dates", () => {
const result = getOverlappingDaysInIntervals(
{
start: new Date(2001, 8 /* Sep */, 1),
end: new Date(2023, 11 /* Dec */, 20),
},
{
start: new Date(2023, 11 /* Dec */, 21),
end: new Date(2001, 8 /* Sep */, 9),
},
);
expect(result).toBe(8137);
});
});

0 comments on commit ad2c654

Please sign in to comment.