aboutsummaryrefslogtreecommitdiffstats
path: root/temperature.go
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2024-01-22 17:35:45 -0500
committerSam Anthony <sam@samanthony.xyz>2024-01-22 17:35:45 -0500
commit2a14395beedc4b3cef74dd7d8b44f14bb8a7ac79 (patch)
tree4216df7bc1ae2404c3fef879987eab50bbe89260 /temperature.go
parent4f6384f449b50a95255837b1fc394b4ebe14caaf (diff)
parent9ad538983290fbd62da7f8d6db5a6dfe123a25c3 (diff)
downloadvolute-2a14395beedc4b3cef74dd7d8b44f14bb8a7ac79.zip
merge backend refactoring from main
Diffstat (limited to 'temperature.go')
-rw-r--r--temperature.go60
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))
+ }
+}