-
Notifications
You must be signed in to change notification settings - Fork 0
/
weekday.go
189 lines (169 loc) · 4.86 KB
/
weekday.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package utils
import (
"fmt"
"log/slog"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type Interval struct {
min int
max int
entry time.Weekday
}
// Weekday assignation strategy
type Weight struct {
total int // Total of cumulated weights
intervals []Interval // Range of weight for each entry
}
type WeekDayStrategy struct {
useWeight bool
weights Weight
}
var CurrentWeekdayStrategy = WeekDayStrategy{
useWeight: false,
}
var days = map[string]time.Weekday{
"mon": time.Monday,
"tue": time.Tuesday,
"wed": time.Wednesday,
"thu": time.Thursday,
"fri": time.Friday,
"sat": time.Saturday,
"sun": time.Sunday,
}
func InitWeekdayAssignationStrategy(
weekdayAssignation map[string]int,
) {
if weekdayAssignation == nil {
CurrentWeekdayStrategy = CreateWeekdayDefaultStrategy()
slog.Debug("No weekday assignation strategy defined, using default", slog.String("strategy", CurrentWeekdayStrategy.String()))
return
}
w := make([]int, 7)
for name, value := range weekdayAssignation {
dayIndex, ok := days[name]
if !ok {
slog.Error("Invalid day name", slog.String("name", name))
continue
}
w[dayIndex] = value
}
CurrentWeekdayStrategy = CreateWeekdayWeightedStrategy(w)
slog.Debug("Weekday assignation strategy defined", slog.String("strategy", CurrentWeekdayStrategy.String()))
}
func InitWeekdayAssignationStrategyFromEnv(
envWeekdayAssignation string,
) {
wday := os.Getenv(envWeekdayAssignation)
if wday == "" {
CurrentWeekdayStrategy = CreateWeekdayDefaultStrategy()
slog.Debug("No weekday assignation strategy defined, using default", slog.String("strategy", CurrentWeekdayStrategy.String()))
return
}
w, err := ParseWeeklyWeight(wday)
if err != nil {
slog.Error("Error parsing weekday assignation weights", slog.String("error", err.Error()))
panic(err)
}
CurrentWeekdayStrategy = CreateWeekdayWeightedStrategy(w)
slog.Debug("Weekday assignation strategy defined", slog.String("strategy", CurrentWeekdayStrategy.String()))
}
// CreateWeight creates a weighted structure to handle the weighted assignation
func CreateWeight(w []int) Weight {
var cumulated int = 0
intervals := make([]Interval, 0)
for entry, w := range w {
weekday := time.Weekday(entry)
if w > 0 {
var min = cumulated
cumulated = cumulated + w
i := Interval{entry: weekday, min: min, max: cumulated - 1}
intervals = append(intervals, i)
}
}
return Weight{intervals: intervals, total: cumulated}
}
// Lookup computes the entry
// Value is expected from 0..total-1
func (w *Weight) Lookup(value int) int {
if value < 0 {
value = 0
}
var last int = 0
for _, interval := range w.intervals {
if value >= interval.min && value <= interval.max {
return int(interval.entry)
}
last = int(interval.entry)
}
return last
}
func (w *Weight) String() string {
s := make([]string, 0, len(w.intervals)+1)
s = append(s, fmt.Sprintf("Wt=%d", w.total))
for _, i := range w.intervals {
lab := fmt.Sprintf("%s=[%d,%d]", i.entry.String(), i.min, i.max)
s = append(s, lab)
}
return strings.Join(s, ", ")
}
func parseTuple(str string) (string, string) {
r := strings.Split(str, "=")
if len(r) < 2 {
return "", ""
}
return strings.ToLower(strings.TrimSpace(r[0])), strings.TrimSpace(r[1])
}
// ParseWeeklyWeight parse a string attributing a weight for each day of the week
// Expected format is a comma separated assignation with [DayName]=Weight with DayName = Mon,Tue,Web,Thu,Frid,Sat,Sun (case insensitive)
// Weight is a positive integer value or Zero
func ParseWeeklyWeight(str string) ([]int, error) {
weights := make([]int, 7)
wdays := strings.Split(str, ",")
for idx, d := range wdays {
name, value := parseTuple(d)
if name == "" {
return weights, fmt.Errorf("expecting day name for entry %d", idx)
}
dayIndex, ok := days[name]
if !ok {
return weights, fmt.Errorf("invalid day name '%s' for entry %d ", name, idx)
}
w, err := strconv.Atoi(value)
if err != nil {
return weights, fmt.Errorf("invalid day weight value '%s' for entry %d, expecting integer : %s", value, idx, err)
}
if w < 0 {
return weights, fmt.Errorf("invalid day weight for entry %d, expecting positive integer : %s", idx, err)
}
weights[dayIndex] = w
}
return weights, nil
}
func CreateWeekdayWeightedStrategy(weights []int) WeekDayStrategy {
return WeekDayStrategy{useWeight: true, weights: CreateWeight(weights)}
}
func CreateWeekdayDefaultStrategy() WeekDayStrategy {
return WeekDayStrategy{useWeight: false}
}
// Assign a new weekday using the assignation strategy
func (s *WeekDayStrategy) Weekday() int {
var weekday int
if s.useWeight {
value := rand.Intn(s.weights.total)
weekday = s.weights.Lookup(value)
fmt.Printf(" %d=>%d ", value, weekday)
} else {
weekday = rand.Intn(7)
}
return weekday
}
func (s *WeekDayStrategy) String() string {
if s.useWeight {
return "Weighted strategy : " + s.weights.String()
}
return "Random strategy"
}