Skip to content

Commit

Permalink
Implement WeekDayDate: turn weekday into actual date
Browse files Browse the repository at this point in the history
  • Loading branch information
sileix committed Mar 6, 2021
1 parent c44fed0 commit 0573b77
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
25 changes: 21 additions & 4 deletions lib/utils/date_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {},
Expand Down Expand Up @@ -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;
}

Expand Down
14 changes: 13 additions & 1 deletion test/test_date_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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();

0 comments on commit 0573b77

Please sign in to comment.