From 8386b5dee41454b596f705061617a36a9648fdcd Mon Sep 17 00:00:00 2001 From: Gekctek Date: Sun, 19 Nov 2023 16:15:18 -0800 Subject: [PATCH] Fixes `DateComponents.dayOfWeek` fails with `arithmetic overflow` on Saturdays #4 --- internal/Components.mo | 6 +++++- test/Components.test.mo | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/internal/Components.mo b/internal/Components.mo index 2989f6c..caaf058 100644 --- a/internal/Components.mo +++ b/internal/Components.mo @@ -1010,7 +1010,11 @@ module Module { let yearWithoutCentury = year % 100; let century = year / 100; let h = day + 13 * (month + 1) / 5 + yearWithoutCentury + yearWithoutCentury / 4 + century / 4 + 5 * century; - Int.abs(h) % 7 - 1; + let position = Int.abs(h) % 7; + switch (position) { + case (0) 6; // Wrap around -1 (Saturday) + case (i) i - 1; + }; }; public func daysInYear(year : Int) : Nat { diff --git a/test/Components.test.mo b/test/Components.test.mo index 9bc1102..c97a7b6 100644 --- a/test/Components.test.mo +++ b/test/Components.test.mo @@ -638,6 +638,22 @@ test( dayOfYear = 114; }; }, + { + components = { + year = 2_023; + month = 11; + day = 18; + hour = 0; + minute = 0; + nanosecond = 0; + }; + expected = { + weekOfYear = 47; + weekYear = 2023; + dayOfWeek = #saturday; + dayOfYear = 322; + }; + }, ]; for (testCase in Iter.fromArray(testCases)) { let actual : Components.DayOfWeek = Components.dayOfWeek(testCase.components);