Created
September 12, 2024 08:35
-
-
Save mildronize/3d93b3b4cfaad7dfef442f35fb2c28f8 to your computer and use it in GitHub Desktop.
Type-Level Programming for Printing Happy International Programmers’ Day
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
import { Pipe, Strings, Tuples, Numbers, Booleans, Call } from "hotscript"; | |
// ------ Helper Types ------- | |
type ParseDateString<Date extends string> = Pipe< | |
Date, | |
[ | |
Strings.Split<"/">, | |
Tuples.Map<Strings.ToNumber>, | |
]>; | |
// Shorter Resolved Operator | |
type Add<a extends number, b extends number> = Call<Numbers.Add<a, b>>; | |
type Sub<a extends number, b extends number> = Call<Numbers.Sub<a, b>>; | |
type Mod<a extends number, b extends number> = Call<Numbers.Mod<a, b>>; | |
type Equals<a, b> = Call<Booleans.Equals<a, b>>; | |
type And<a, b> = Call<Booleans.And<a, b>>; | |
type Or<a, b> = Call<Booleans.Or<a, b>>; | |
type Not<a> = Call<Booleans.Not<a>>; | |
// lists the number of days for each month in a non-leap year: | |
type DaysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; | |
// lists the number of days for each month in a leap year: | |
type DaysInMonthsLeapYear = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; | |
type IsLeapYear<Year extends number> = Or< | |
And< | |
Equals<Mod<Year, 4>, 0>, // year % 4 === 0 | |
Not<Equals<Mod<Year, 100>, 0>> // year % 100 !== 0 | |
>, | |
Equals<Mod<Year, 400>, 0> // year % 400 === 0 | |
>; | |
// Get Days in Month (Support Leap Year) | |
type GetDaysInMonths<Year extends number> = IsLeapYear<Year> extends true ? DaysInMonthsLeapYear : DaysInMonths; | |
// ------ Main Program ----- | |
type StringDate = ParseDateString<'12/9/2024'> | |
type Day = StringDate[0]; | |
type Month = StringDate[1]; | |
type Year = StringDate[2]; | |
type GetDays = Add< | |
Call<Tuples.Sum<Call<Tuples.Take<Sub<Month, 1>, GetDaysInMonths<Year>>>>>, | |
Day | |
>; | |
type Output = Equals<GetDays, 256> extends true ? 'Happy International Programmers’ Day' : never; | |
// ? Output = Happy International Programmers’ Day | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment