What would be the best way to combine these golang functions?
// convertVenueHours converts venue.OpeningHours to the unified format
func convertVenueHours(venueHours venue.OpeningHours) [][]operatingTime {
weeklyHours := make([][]operatingTime, daysPerWeek)
code
days := [][]venue.OperatingTime{
venueHours.Monday,
venueHours.Tuesday,
venueHours.Wednesday,
venueHours.Thursday,
venueHours.Friday,
venueHours.Saturday,
venueHours.Sunday,
}
for dayIndex, dayTimes := range days {
for _, t := range dayTimes {
weeklyHours[dayIndex] = append(weeklyHours[dayIndex], operatingTime{
open: t.Open,
close: t.Close,
})
}
}
return weeklyHours
}
// convertCourierHours converts courier.DeliveryHours to the unified format
func convertCourierHours(courierHours courier.DeliveryHours) [][]operatingTime {
weeklyHours := make([][]operatingTime, daysPerWeek)
code
days := [][]courier.OperatingTime{
courierHours.Monday,
courierHours.Tuesday,
courierHours.Wednesday,
courierHours.Thursday,
courierHours.Friday,
courierHours.Saturday,
courierHours.Sunday,
}
for dayIndex, dayTimes := range days {
for _, t := range dayTimes {
weeklyHours[dayIndex] = append(weeklyHours[dayIndex], operatingTime{
open: t.Open,
close: t.Close,
})
}
}
return weeklyHours
}
Assistant
Your two functions are almost identical; the only differences are the input types and the way you access daily slices. To combine them, you can introduce a common interface or an intermediate abstraction that both venue.OperatingTime and courier.OperatingTime satisfy.
Here are some approaches:
1. Define an interface and helper function
If both types have the same fields (Open and Close), define an interface:
go
type TimeRange interface {
OpenTime() string
CloseTime() string
}