File size: 1,777 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package schedule

import (
	"sort"
	"strings"
	"time"
)

// A FixedShift represents an on-call user with a start and end time.
type FixedShift struct {
	Start, End time.Time
	UserID     string
}

func maxTime(a, b time.Time) time.Time {
	if a.After(b) {
		return a
	}
	return b
}

func clampShiftTimes(start, end time.Time, shifts []FixedShift) []FixedShift {
	result := shifts[:0]
	// trim/clamp shift times
	for _, s := range shifts {
		if s.Start.Before(start) {
			s.Start = start
		}
		if s.End.After(end) {
			s.End = end
		}
		if !s.End.After(s.Start) {
			continue
		}

		result = append(result, s)
	}
	return result
}

func mergeShiftsByTime(shifts []FixedShift) []FixedShift {
	if len(shifts) == 0 {
		return shifts
	}

	sort.Slice(shifts, func(i, j int) bool { return shifts[i].Start.Before(shifts[j].Start) })
	result := shifts[:1]
	for _, s := range shifts[1:] {
		l := len(result) - 1

		if !s.End.After(s.Start) {
			// omit empty time range
			continue
		}
		if s.Start.After(result[l].End) {
			result = append(result, s)
			continue
		}

		// TODO: remove once we switch to uuid.UUID
		s.UserID = strings.ToLower(s.UserID)

		result[l].End = maxTime(result[l].End, s.End)
	}

	return result
}
func mergeShifts(shifts []FixedShift) []FixedShift {
	m := make(map[string][]FixedShift)
	for _, s := range shifts {
		m[s.UserID] = append(m[s.UserID], s)
	}
	result := shifts[:0]
	for _, s := range m {
		result = append(result, mergeShiftsByTime(s)...)
	}

	// Return deterministic output by sorting by Start,
	// or UserID if the Start times are equal.
	sort.Slice(result, func(i, j int) bool {
		if !result[i].Start.Equal(result[j].Start) {
			return result[i].Start.Before(result[j].Start)
		}
		return result[i].UserID < result[j].UserID
	})

	return result
}