From 76e08d67d8ab1b6ea397248aee2751a82a197562 Mon Sep 17 00:00:00 2001 From: timeTable2 dev Date: Mon, 13 Jul 2026 18:22:57 +0800 Subject: [PATCH] feat: add weekday constants and helpers --- src/lib/weekday.js | 17 +++++++++++++++++ test/weekday.test.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 src/lib/weekday.js create mode 100644 test/weekday.test.js diff --git a/src/lib/weekday.js b/src/lib/weekday.js new file mode 100644 index 0000000..f05d002 --- /dev/null +++ b/src/lib/weekday.js @@ -0,0 +1,17 @@ +// JS getDay() index: 0=Sunday .. 6=Saturday +export const DOW = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'] + +// BYDAY codes indexed by JS getDay(): DOW_EN[getDay()] => 'SU'..'SA' +export const DOW_EN = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'] + +export const BYDAY_TO_INDEX = { SU: 0, MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6 } + +/** Return the BYDAY code ('SU'..'SA') for a JS Date. */ +export function bydayFromDate(date) { + return DOW_EN[date.getDay()] +} + +/** Return the Chinese weekday label for a JS Date. */ +export function dowLabel(date) { + return DOW[date.getDay()] +} diff --git a/test/weekday.test.js b/test/weekday.test.js new file mode 100644 index 0000000..62b3bca --- /dev/null +++ b/test/weekday.test.js @@ -0,0 +1,31 @@ +import { describe, it, expect } from 'vitest' +import { DOW, DOW_EN, BYDAY_TO_INDEX, bydayFromDate, dowLabel } from '../src/lib/weekday.js' + +describe('weekday', () => { + it('DOW has 7 entries starting Sunday', () => { + expect(DOW).toHaveLength(7) + expect(DOW[0]).toBe('周日') + expect(DOW[6]).toBe('周六') + }) + + it('DOW_EN indexed by JS getDay (0=Sunday)', () => { + expect(DOW_EN).toEqual(['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA']) + }) + + it('BYDAY_TO_INDEX maps SU..SA to 0..6', () => { + expect(BYDAY_TO_INDEX.SU).toBe(0) + expect(BYDAY_TO_INDEX.SA).toBe(6) + }) + + it('bydayFromDate returns BYDAY code for a Date', () => { + // 2026-07-27 is a Monday -> getDay()=1 -> 'MO' + expect(bydayFromDate(new Date(2026, 6, 27))).toBe('MO') + // 2026-08-01 is a Saturday -> getDay()=6 -> 'SA' + expect(bydayFromDate(new Date(2026, 7, 1))).toBe('SA') + }) + + it('dowLabel returns Chinese label for a Date', () => { + expect(dowLabel(new Date(2026, 6, 27))).toBe('周一') + expect(dowLabel(new Date(2026, 6, 26))).toBe('周日') + }) +})