typescript/app/calendar.ts · 1985 字节 · 下载原文
// 月历排版 —— 小应用:纯整数运算 + 字符串拼接(与 `python/app/calendar.py` 同一档)
// Month grid printer -- integer math + string building, same niche as python/app/calendar.py
//
// 规则(公历):平年 2 月 28 天、闰年 29 天;这里给的是**固定**的 2026 年 11 月,
// 起始星期由参数给(不查表、不依赖系统时钟 —— 例程要能在任何宿主上跑出同样的输出)。
const YEAR: number = 2026;
const MONTH: number = 11;
const START_WEEKDAY: number = 6; // 0 = 周日;6 = 周六(2026-11-01 是周六)
function isLeap(y: number): boolean {
if (y % 400 === 0) { return true; }
if (y % 100 === 0) { return false; }
return y % 4 === 0;
}
function daysInMonth(y: number, m: number): number {
if (m === 2) {
return isLeap(y) ? 29 : 28;
}
if (m === 4 || m === 6 || m === 9 || m === 11) {
return 30;
}
return 31;
}
function pad2(n: number): string {
if (n < 10) { return " " + n; }
return "" + n;
}
const total: number = daysInMonth(YEAR, MONTH);
print_str(YEAR + " 年 " + MONTH + " 月 / " + YEAR + "-" + pad2(MONTH) + "\n");
print_str("日 一 二 三 四 五 六\n");
let line: string = "";
let col: number = 0;
let i: number = 0;
while (i < START_WEEKDAY) {
line = line + " ";
col = col + 1;
i = i + 1;
}
let day: number = 1;
while (day <= total) {
line = line + pad2(day) + " ";
col = col + 1;
if (col === 7) {
print_str(line + "\n");
line = "";
col = 0;
}
day = day + 1;
}
if (col > 0) {
print_str(line + "\n");
}
// ⚠ 别写成 `cond ? "yes" : "no"`:本门的三元对**字符串**不成立(实测打出一个整数),
// 与「对象字段当字符串打印」是同一类限制 ⇒ 用普通 if 把字符串变量赋好再拼。
let leapText: string = "no";
if (isLeap(YEAR)) {
leapText = "yes";
}
print_str("\n闰年 / leap: " + leapText + "\n");