Created
December 1, 2021 04:53
-
-
Save aldy505/f19c53f9cde311b968da93be6c7bce1d to your computer and use it in GitHub Desktop.
Simple exercise to play around with the time standard library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
// Hello again. This time, we will be exploring the | |
// time standard library. | |
// | |
// The function that we'll make is pretty simple, | |
// we are going to have a date input, in the form (or type) | |
// of time.Time, then we'll add 14 days to it. | |
// | |
// But here's the tricky part: | |
// We'll skip satuday and sundays, so the entire 14 days | |
// should be on weekdays only, not on weekends. | |
// | |
// This is the pseudocode: | |
// | |
// var date = given date | |
// var days = 0 | |
// var output = date | |
// | |
// while (days < 14) | |
// var dateInDay = convertToDay(output) | |
// switch dateInDay | |
// case "saturday" | |
// output = output + 1 day | |
// continue | |
// case "sunday" | |
// output = output + 1 day | |
// continue | |
// default | |
// output = output + 1 day | |
// days += 1 | |
// end | |
// end | |
// | |
// return output | |
// | |
// But this pseudocode has a problem: | |
// What if the date stops at weekends? | |
// There's your challenge! | |
// | |
// Good luck! | |
func Add14Days(date time.Time) time.Time { | |
var output = date | |
// To convert a date to a weekday, | |
// use (time.Time).Weekday() | |
// https://pkg.go.dev/time#Time.Weekday | |
// It will return an enum of Weekday, use that | |
// as your advantage! | |
// To add a date, use (time.Time).Add() | |
// https://pkg.go.dev/time#Time.Add | |
// for example: | |
// time.Add(time.Hour * 6) | |
// this will increment the time into 6 hours | |
return output | |
} | |
type testObj struct { | |
i time.Time | |
e time.Time | |
} | |
func main() { | |
fmt.Print("Oh hello there! I'm going to test your code again.\n\n") | |
tests := []testObj{ | |
{ | |
i: time.Date(2021, 12, 1, 0, 0, 0, 0, time.UTC), | |
e: time.Date(2021, 12, 21, 0, 0, 0, 0, time.UTC), | |
}, | |
{ | |
i: time.Date(2021, 11, 1, 0, 0, 0, 0, time.UTC), | |
e: time.Date(2021, 11, 18, 0, 0, 0, 0, time.UTC), | |
}, | |
{ | |
i: time.Date(2021, 11, 30, 0, 0, 0, 0, time.UTC), | |
e: time.Date(2021, 12, 20, 0, 0, 0, 0, time.UTC), | |
}, | |
} | |
for i, t := range tests { | |
if r := Add14Days(t.i); r != t.e { | |
fmt.Printf("--- Test #%d failed\n\nExpecting: %s\nGot: %s\n\n", i, t.e, r) | |
} else { | |
fmt.Printf("--- Test #%d succeed\n\n", i) | |
} | |
} | |
fmt.Print("The test is completed!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment