diff --git a/src/components/nextTopic.js b/src/components/nextTopic.js index 4d25cf1..52324d7 100644 --- a/src/components/nextTopic.js +++ b/src/components/nextTopic.js @@ -10,7 +10,7 @@ export default () => { // because it would be outdated rather quickly const isSSR = typeof window === "undefined" if (isSSR) { - testNextTopic() + test() return "unbekannt" } @@ -21,11 +21,7 @@ export default () => { function getNextTopicDate() { // first thursday and third tuesday in month - const nextTopic = new Date(today) - nextTopic.setHours(0) - nextTopic.setMinutes(0) - nextTopic.setSeconds(0) - nextTopic.setMilliseconds(0) + const nextTopic = zeroizeTime(today) // first thursday if (calculatePriorWeekdays(THURSDAY) === 0) { @@ -119,9 +115,11 @@ function formatDateInfo(date) { } /** - * how many sunday to monday transitions are between the two daysTillTuesday + * how many sunday to monday transitions are between the two dates */ -function weeksBetween(date1, date2) { +function weeksBetween(datetime1, datetime2) { + const date1 = zeroizeTime(datetime1) + const date2 = zeroizeTime(datetime2) const MILLISECONDS_IN_WEEK = 7 * 24 * 60 * 60 * 1000 var weeks = Math.floor((date2 - date1) / MILLISECONDS_IN_WEEK) // if there is a sunday to monday transition between @@ -140,9 +138,37 @@ function getISODateString(date) { return `${year}-${monthPadded}-${dayPadded}` } -// test, becuase this is complicated +function zeroizeTime(date) { + const copy = new Date(date) + copy.setHours(0) + copy.setMinutes(0) + copy.setSeconds(0) + copy.setMilliseconds(0) + return copy +} -function testNextTopic() { +// test, because this is complicated + +function test() { + testLateSunday() + testYear2020() + + // reset to correct value + today = new Date() +} + +function testLateSunday() { + today = new Date("2020-01-19T23:59:59+01:00") + const result = formatDateInfo(getNextTopicDate()) + console.assert( + result === "Nächste Woche Dienstag, 2020-01-21", + `starting at ${getISODateString( + today + )}: was ${result}, expected "Nächste Woche Dienstag, 2020-01-21"` + ) +} + +function testYear2020() { const topicsIn2020 = [ "2020-01-02", "2020-01-21", @@ -169,20 +195,21 @@ function testNextTopic() { "2020-12-03", "2020-12-15", ] - today = new Date("2020-01-01") + today = zeroizeTime(new Date("2020-01-01")) + let currentIndex = 0 - for (const nextTopic of topicsIn2020) { + while (today <= new Date("2020-12-15")) { const result = getISODateString(getNextTopicDate()) + const expect = topicsIn2020[currentIndex] console.assert( - result === nextTopic, + result === expect, `starting at ${getISODateString( today - )}: was ${result}, expected ${nextTopic}` + )}: was ${result}, expected ${expect}` ) - today = new Date(result) - today.setDate(today.getDate() + 1) + if (getISODateString(today) === result) { + currentIndex++ + } + addDays(today, 1) } - - // reset to correct value - today = new Date() }