diff options
| author | Sam Anthony <sam@samanthony.xyz> | 2024-01-20 17:56:39 -0500 |
|---|---|---|
| committer | Sam Anthony <sam@samanthony.xyz> | 2024-01-20 17:56:39 -0500 |
| commit | 3aaae870ba76d8f0907b10a61d829ad353936306 (patch) | |
| tree | 8be8cb950d0aa8039cd977c72e2f9438cae4a1e8 /temperature.go | |
| parent | db183cf7570e0f4e448ab5ced0ae41969261a815 (diff) | |
| download | volute-3aaae870ba76d8f0907b10a61d829ad353936306.zip | |
flatten source directory structure by removing modules
Diffstat (limited to 'temperature.go')
| -rw-r--r-- | temperature.go | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/temperature.go b/temperature.go new file mode 100644 index 0000000..ac8cae0 --- /dev/null +++ b/temperature.go @@ -0,0 +1,60 @@ +package main + +import ( + "errors" + "fmt" +) + +type TemperatureUnit int + +const ( + Celcius TemperatureUnit = iota + Kelvin + Fahrenheit +) + +var TemperatureUnits = []string{"°C", "°K", "°F"} + +func ParseTemperatureUnit(s string) (TemperatureUnit, error) { + // Each case corresponds to a value in UnitStrings(). + switch s { + case "°C": + return Celcius, nil + case "°K": + return Kelvin, nil + case "°F": + return Fahrenheit, nil + default: + return *new(TemperatureUnit), errors.New(fmt.Sprintf("invalid unit: '%s'", s)) + } +} + +type Temperature struct { + Val float32 + Unit TemperatureUnit +} + +func (t Temperature) AsUnit(u TemperatureUnit) (float32, error) { + // Convert to celcius + var c float32 + switch t.Unit { + case Celcius: + c = t.Val + case Kelvin: + c = t.Val - 272.15 + case Fahrenheit: + c = (t.Val - 32.0) * (5.0 / 9.0) + } + + // Convert to desired unit + switch u { + case Celcius: + return c, nil + case Kelvin: + return c + 272.15, nil + case Fahrenheit: + return c*(9.0/5.0) + 32.0, nil + default: + return 0, errors.New(fmt.Sprintf("invalid unit: '%v'", u)) + } +} |