From 0573b777d837ba6373057a8e33decb5e089d81dd Mon Sep 17 00:00:00 2001 From: Silei Date: Fri, 5 Mar 2021 14:43:08 -0800 Subject: [PATCH] Implement WeekDayDate: turn weekday into actual date --- lib/utils/date_utils.ts | 25 +++++++++++++++++++++---- test/test_date_utils.js | 14 +++++++++++++- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/lib/utils/date_utils.ts b/lib/utils/date_utils.ts index 0d5c8715..bf4ee3c5 100644 --- a/lib/utils/date_utils.ts +++ b/lib/utils/date_utils.ts @@ -20,7 +20,7 @@ import assert from 'assert'; -import { DateEdge, DatePiece, WeekDayDate, AbsoluteTime } from '../ast/values'; +import { DateEdge, DatePiece, WeekDayDate, AbsoluteTime, WeekDay } from '../ast'; const TIME_UNITS = ['ms', 's', 'min', 'h', 'day', 'week', 'mon', 'year']; const SET_ZERO : Array<(d : Date) => void> = [(d) => {}, @@ -112,10 +112,27 @@ function createDatePiece(year : number|null, month : number|null, day : number|n return date; } -function createWeekDayDate(weekday : string, time : AbsoluteTime|null) { - const date = new Date; +function weekdayToNumber(weekday : WeekDay) : number { + switch (weekday) { + case "monday": return 1; + case "tuesday": return 2; + case "wednesday": return 3; + case "thursday": return 4; + case "friday": return 5; + case "saturday": return 6; + case "sunday": return 7; + } + throw new Error(`Invalid weekday: ${weekday}`); +} - // FIXME: implement this +function createWeekDayDate(weekday : WeekDay, time : AbsoluteTime|null) { + const date = new Date; + const weekdayNumber = weekdayToNumber(weekday); + const diff = (weekdayNumber - date.getDay()) % 7; + // get the date of next specified weekday, today excluded + date.setDate(date.getDate() + (diff > 0 ? diff : diff + 7)); + if (time) + date.setHours(time.hour, time.minute, time.second, 0); return date; } diff --git a/test/test_date_utils.js b/test/test_date_utils.js index 26e6cc7e..ac9c47b8 100644 --- a/test/test_date_utils.js +++ b/test/test_date_utils.js @@ -18,7 +18,7 @@ import assert from 'assert'; -import { DateEdge, DatePiece, Time } from '../lib/ast'; +import { DateEdge, DatePiece, Time, WeekDayDate } from '../lib/ast'; import { parseDate, normalizeDate } from '../lib/utils/date_utils'; function test(value, expected) { @@ -111,6 +111,18 @@ export default function main() { eleven_thirty.setSeconds(0); eleven_thirty.setMilliseconds(0); test(new DatePiece(null, null, 25, new Time.Absolute(11, 30, 0)), eleven_thirty); + + const weekdays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']; + for (let j = 0; j < 7; j++) { + const date = new Date; + date.setHours(12, 0, 0, 0); + const weekday = weekdays[j]; + const nextweekday = date; + nextweekday.setDate(nextweekday.getDate() + 1); + while (nextweekday.getDay() !== j) + nextweekday.setDate(nextweekday.getDate() + 1); + test(new WeekDayDate(weekday, new Time.Absolute(12, 0, 0)), nextweekday); + } } if (!module.parent) main();