Skip to content

Instantly share code, notes, and snippets.

@nitrix
Created January 23, 2021 22:41
Show Gist options
  • Save nitrix/b9645dbf1a479f5a94a82338da57d009 to your computer and use it in GitHub Desktop.
Save nitrix/b9645dbf1a479f5a94a82338da57d009 to your computer and use it in GitHub Desktop.
Shit code, months with more than 2 paydays
package main
import (
"fmt"
"github.com/jinzhu/now"
"log"
"os"
"strconv"
"time"
)
func main() {
inputDate, yearsAhead, err := userInputs()
if err != nil {
log.Fatalln(err)
}
dates, err := findMonthsWithMoreThanNPaydays(inputDate, 2, yearsAhead)
if err != nil {
log.Fatalln(err)
}
displayTheDates(dates)
}
func displayTheDates(dates []time.Time) {
currentYear := ""
for _, date := range dates {
year := strconv.Itoa(date.Year())
if currentYear != year {
fmt.Printf("%s:\n", year)
currentYear = year
}
fmt.Printf("\t%s %s\n", date.Month(), formatDay(date.Day()))
}
}
func userInputs() (string, int, error) {
inputDate := "2021-01-22"
yearsAhead := 1
if len(os.Args) > 2 {
var err error
inputDate = os.Args[1]
yearsAhead, err = strconv.Atoi(os.Args[2])
if err != nil {
return "", 0, err
}
} else {
fmt.Print("Most recent pay day (2021-01-22): ")
_, _ = fmt.Scanln(&inputDate)
fmt.Print("Years ahead (1): ")
_, _ = fmt.Scanln(&yearsAhead)
}
return inputDate, yearsAhead, nil
}
func findMonthsWithMoreThanNPaydays(startDate string, nPaydays int, yearsAhead int) ([]time.Time, error) {
const Week = time.Hour * 24 * 7
output := make([]time.Time, 0)
firstPayDay, err := now.Parse(startDate)
if err != nil {
return nil, err
}
// For the next 26 pay days, figure out what those dates will be.
payDays := make([]time.Time, yearsAhead * 26)
for payNumber := 0; payNumber < yearsAhead * 26; payNumber++ {
payDay := firstPayDay.Add(2 * Week * time.Duration(payNumber + 1))
payDays[payNumber] = payDay
}
// Figure out months with more than 2 pays.
currentMonth := ""
currentCount := 0
for _, payDay := range payDays {
if currentMonth == payDay.Month().String() {
currentCount++
} else {
currentMonth = payDay.Month().String()
currentCount = 1
}
if currentCount > nPaydays {
output = append(output, payDay)
}
}
return output, nil
}
func formatDay(day int) string {
suffix := "th"
switch day {
case 1, 21, 31:
suffix = "st"
case 2, 22:
suffix = "nd"
case 3, 23:
suffix = "rd"
}
return fmt.Sprintf("%d%s", day, suffix)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment