iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💻

Verifying Early, Middle, and Late Monthly Periods

に公開

Recently, it seems that Zenn allows embedding code from GitHub repositories, so I'll try introducing some Go code I wrote recently as practice.

I want to represent the beginning, middle, and end of the month

You know how there are terms like "early January" or "late September"? I want to be able to control those. So, let's start by considering a type like this.

https://github.com/spiegel-im-spiegel/zenn-docs/blob/main/code/period-sample/period/period.go#L8-L30

Hmm. Something like this, I guess.

Next, I'll define a date type that can handle this Period type.

https://github.com/spiegel-im-spiegel/zenn-docs/blob/main/code/period-sample/period/period.go#L32-L48

With this, I can represent date information including the early, mid, and late periods as an integer. Expanding it back to a date can be done like this:

https://github.com/spiegel-im-spiegel/zenn-docs/blob/main/code/period-sample/period/period.go#L50-L67

That should work. This allows it to be written like this:

https://github.com/spiegel-im-spiegel/zenn-docs/blob/main/code/period-sample/sample1.go

I'll also write down addition and subtraction using the Duration type.

https://github.com/spiegel-im-spiegel/zenn-docs/blob/main/code/period-sample/period/period.go#L69-L77

Calculations using this can be written as:

https://github.com/spiegel-im-spiegel/zenn-docs/blob/main/code/period-sample/sample2.go

And that's how it turned out.

Verifying with Go

To tell you the truth, I was originally trying to create a Java class with similar functionality. Then, while thinking about how to verify the calculations for writing tests, I ended up writing this in Go (actually, I wrote it much more roughly back then).

In the past, I used to write verification code in scripting languages, but lately, I've somehow been writing it in Go. Usually, I throw away this kind of code after I'm done with it, but this time I thought I might recycle it, so I decided to publish it. Well, it's not worth making it into a package, so I'll just leave it as sample code.

Happy coding!

GitHubで編集を提案

Discussion