Skip to content

Instantly share code, notes, and snippets.

@tsal

tsal/main.go

Last active Oct 29, 2019
Embed
What would you like to do?
go temperature conversion
package main
import (
"example/pkg/temperature"
"fmt"
)
func main() {
t := convert.New(0, convert.Celsius)
fmt.Println(t.F())
}
package temperature
type temperatureUnit int
const (
Kelvin temperatureUnit = iota
Celsius
Fahrenheit
Rankine
)
type conversionFunc func(float64) float64
const (
rankine float64 = 9/5
rankineInverted float64 = 5/9
)
func rankineUp(in float64) float64 { return in * rankine }
func rankineDown(in float64) float64 { return in * rankineInverted }
var funcMap = map[temperatureUnit]map[temperatureUnit]conversionFunc{
Kelvin: {
Celsius: func(in float64) float64 { return in - 273.15 },
Fahrenheit: func(in float64) float64 { return rankineUp(in) - 459.67 },
Rankine: rankineUp,
},
Celsius: {
Kelvin: func(in float64) float64 { return in + 273.15},
Fahrenheit: func(in float64) float64 { return rankineUp(in) + 32 },
Rankine: func(in float64) float64 { return rankineUp(in + 273.15) },
},
Fahrenheit: {
Kelvin: func(in float64) float64 { return rankineDown(in + 459.67) },
Celsius: func(in float64) float64 { return rankineDown(in - 32)},
Rankine: func(in float64) float64 { return in + 459.67 },
},
Rankine: {
Kelvin: rankineDown,
Celsius: func(in float64) float64 { return rankineDown(in - 491.67) },
Fahrenheit: func(in float64) float64 { return in - 459.67 },
},
}
type ConvertibleTemperature struct {
Value float64
Unit temperatureUnit
}
func New(value float64, unit temperatureUnit) *ConvertibleTemperature {
return &ConvertibleTemperature{
Value: value,
Unit: unit,
}
}
func (T ConvertibleTemperature) Convert(to temperatureUnit) float64 {
return funcMap[T.Unit][to](T.Value)
}
func fromTo(from, to temperatureUnit, t ConvertibleTemperature) float64 {
if from == to { return t.Value } else {
return t.Convert(to)
}
}
func (T ConvertibleTemperature) C() float64 { return fromTo(T.Unit, Celsius, T) }
func (T ConvertibleTemperature) F() float64 { return fromTo(T.Unit, Fahrenheit, T) }
func (T ConvertibleTemperature) K() float64 { return fromTo(T.Unit, Kelvin, T) }
func (T ConvertibleTemperature) R() float64 { return fromTo(T.Unit, Rankine, T) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment