Skip to content

Instantly share code, notes, and snippets.

@sklyar
Last active September 3, 2018 16:00
Show Gist options
  • Save sklyar/cd4c7c1a271eb40cbefab99f2352dadb to your computer and use it in GitHub Desktop.
Save sklyar/cd4c7c1a271eb40cbefab99f2352dadb to your computer and use it in GitHub Desktop.
Get N nearest dates
package main
import (
"time"
"fmt"
)
func main() {
times := NewReservationBuilder().
SetDate(2018, 9, 3).
Weekdays(time.Sunday).
NearestN(10)
for i := 0; i < len(times); i++ {
fmt.Println(times[i].Format("2006-01-02"))
}
}
type ReservationBuilder struct {
date time.Time
weekdays []time.Weekday
}
func NewReservationBuilder() ReservationBuilder {
return ReservationBuilder{
date: time.Now().UTC(),
}
}
func (b ReservationBuilder) SetTime(t time.Time) ReservationBuilder {
b.date = t
return b
}
func (b ReservationBuilder) SetDate(year int, month time.Month, day int) ReservationBuilder {
b.date = time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
return b
}
func (b ReservationBuilder) Weekdays(weekdays ...time.Weekday) ReservationBuilder {
b.weekdays = weekdays
return b
}
func (b ReservationBuilder) isExistWeekday(weekday time.Weekday) bool {
for _, wd := range b.weekdays {
if weekday == wd {
return true
}
}
return false
}
func (b ReservationBuilder) NearestN(count int) []time.Time {
if len(b.weekdays) == 0 {
return nil
}
times := make([]time.Time, 0, count)
for {
if len(times) == count {
break
}
if b.isExistWeekday(b.date.Weekday()) {
times = append(times, b.date)
}
b.date = b.date.AddDate(0, 0, 1)
}
return times
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment