Files
yunzerwebsiteallinone/go/pkg/holiday/holiday.go
T
2026-11-16 17:22:50 +08:00

160 lines
2.7 KiB
Go

package holiday
import (
"time"
)
const (
TypeWorkday int8 = 0
TypeHoliday int8 = 1
)
const (
SourceHolidayCN = "holiday-cn"
SourceBuiltin = "builtin"
)
type Day struct {
Date string `json:"date"`
Name string `json:"name"`
Type int8 `json:"type"`
Year int `json:"year"`
Wage int8 `json:"wage"`
Source string `json:"source"`
}
func (d Day) IsOffDay() bool {
return d.Type == TypeHoliday
}
const dateLayout = "2006-01-02"
func parseDate(s string) (time.Time, error) {
return time.ParseInLocation(dateLayout, s, time.Local)
}
func normalizeDate(s string) string {
if len(s) > 10 {
return s[:10]
}
return s
}
func expandRange(start, end string) []string {
if end == "" {
end = start
}
st, err := parseDate(normalizeDate(start))
if err != nil {
return nil
}
et, err := parseDate(normalizeDate(end))
if err != nil {
return nil
}
out := make([]string, 0, 16)
if et.Before(st) {
return nil
}
if et.Sub(st) > 60*24*time.Hour {
return nil
}
for d := st; !d.After(et); d = d.AddDate(0, 0, 1) {
out = append(out, d.Format(dateLayout))
}
return out
}
func wageOfHolidayName(name string, indexInRange int) int8 {
switch name {
case "春节", "国庆节", "国庆节、中秋节":
if indexInRange < 3 {
return 3
}
return 2
default:
if indexInRange == 0 {
return 3
}
return 2
}
}
func Years() []int {
seen := make(map[int]bool, len(yearNotices))
out := make([]int, 0, len(yearNotices))
for _, n := range yearNotices {
if !seen[n.Year] {
seen[n.Year] = true
out = append(out, n.Year)
}
}
return out
}
func builtinByYear(year int) []Day {
out := make([]Day, 0, 32)
for _, d := range fallbackData {
if d.Year == year {
out = append(out, d)
}
}
return out
}
func annotateWage(list []Day) []Day {
if len(list) == 0 {
return list
}
prevName := ""
indexInRange := 0
for i := range list {
if list[i].Type != TypeHoliday {
prevName = ""
indexInRange = 0
list[i].Wage = 1
continue
}
if list[i].Name != prevName {
prevName = list[i].Name
indexInRange = 0
} else {
indexInRange++
}
list[i].Wage = wageOfHolidayName(list[i].Name, indexInRange)
}
return list
}
func dedupSort(list []Day) []Day {
seen := make(map[string]int, len(list))
out := make([]Day, 0, len(list))
for _, d := range list {
if d.Date == "" {
continue
}
if idx, ok := seen[d.Date]; ok {
if d.Type == TypeHoliday && out[idx].Type == TypeWorkday {
out[idx] = d
}
continue
}
seen[d.Date] = len(out)
out = append(out, d)
}
sortByDate(out)
return out
}
func sortByDate(list []Day) {
for i := 1; i < len(list); i++ {
cur := list[i]
j := i - 1
for j >= 0 && list[j].Date > cur.Date {
list[j+1] = list[j]
j--
}
list[j+1] = cur
}
}