init.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import fs from "fs";
  2. import generate from "./generate";
  3. import { Holiday } from '../src/holidays/arrangement';
  4. import dayjs from "../src/utils/dayjs";
  5. const data = generate();
  6. // 反向映射 Holiday 枚举
  7. const holidayMap: Record<string, keyof typeof Holiday> = Object.fromEntries(
  8. Object.entries(Holiday).map(([key, value]) => [value, key as keyof typeof Holiday])
  9. );
  10. const mapToEnum = (obj: Record<string, string>): Record<string, any> => {
  11. const result: Record<string, any> = {};
  12. for (const [key, value] of Object.entries(obj)) {
  13. if (holidayMap[value]) {
  14. result[key] = `${holidayMap[value]}`;
  15. } else {
  16. result[key] = `${value}`;
  17. }
  18. }
  19. return result;
  20. };
  21. // 转换数据
  22. const holidays = mapToEnum(data.holidays);
  23. const workdays = mapToEnum(data.workdays);
  24. const inLieuDays = mapToEnum(data.inLieuDays);
  25. const startDate = dayjs('2000-01-01');
  26. const getDaysSince2000 = (date: string): number => {
  27. const givenDate = dayjs(date);
  28. const diffDays = givenDate.diff(startDate, 'day');
  29. return diffDays;
  30. }
  31. const compress = (dates: Record<string, Holiday>) => {
  32. const compressedDates: Record<string, number[]> = {};
  33. for (const [date, holidayInfo] of Object.entries(dates)) {
  34. const [holidayName, ,] = holidayInfo.split(',');
  35. const daysSince2000 = getDaysSince2000(date);
  36. if (!compressedDates[holidayName]) {
  37. compressedDates[holidayName] = [];
  38. }
  39. compressedDates[holidayName].push(daysSince2000);
  40. }
  41. return compressedDates;
  42. }
  43. const tsContent = `/** 自动生成的文件,请勿手动修改,数字含义是与 2000 年 1 月 1 日 相差天数 */
  44. export const holidays: Record<string, number[]> = ${JSON.stringify(compress(holidays))};
  45. export const workdays: Record<string, number[]> = ${JSON.stringify(compress(workdays))};
  46. export const inLieuDays: Record<string, number[]> = ${JSON.stringify(compress(inLieuDays))};`
  47. // 保存到 constants.ts 文件
  48. fs.writeFile('./src/holidays/constants.ts', tsContent, (err) => {
  49. if (err) throw err;
  50. console.log('The file has been saved!');
  51. });