aboutsummaryrefslogtreecommitdiffstats
path: root/mass.go
blob: 0b9702013dab218d341d46c30d2b2259a9f0dd0c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main

import (
	"errors"
	"fmt"
	"time"
)

type massUnit float32

const (
	gram     massUnit = 1
	kilogram massUnit = 1_000
	pound    massUnit = 453.5924
)

type mass struct {
	val  float32
	unit massUnit
}

func (m mass) asUnit(u massUnit) float32 {
	g := m.val * float32(m.unit) // Convert to grams.
	return g / float32(u)        // Convert to desired unit.
}

type massFlowRateUnit float32

const (
	kilogramsPerSecond massFlowRateUnit = 1
	poundsPerMinute    massFlowRateUnit = 0.007_559_872_833
)

// massFlowRateUnitStrings returns a slice of strings, each representing a
// massFlowRateUnit.
// This is necessary because giu.Combo only works with strings.
func massFlowRateUnitStrings() []string {
	return []string{"kg/s", "lb/min"}
}

const (
	defaultMassFlowRateUnit massFlowRateUnit = kilogramsPerSecond
	//Used to index massFlowRateUnitStrings
	defaultMassFlowRateUnitIndex int32 = 0 // kg/s
)

func massFlowRateUnitFromString(s string) (massFlowRateUnit, error) {
	// Each case corresponds to a value in massFlowRateUnitStrings.
	switch s {
	case "kg/s":
		return kilogramsPerSecond, nil
	case "lb/min":
		return poundsPerMinute, nil
	default:
		return *new(massFlowRateUnit), errors.New(
			fmt.Sprintf("invalid massFlowRateUnit: '%s'", s))
	}
}

type massFlowRate struct {
	val  float32
	unit massFlowRateUnit
}

func newMassFlowRate(m mass, t time.Duration, u massFlowRateUnit) (massFlowRate, error) {
	switch u {
	case kilogramsPerSecond:
		return massFlowRate{
			m.asUnit(kilogram) / float32(t.Seconds()),
			u,
		}, nil
	case poundsPerMinute:
		return massFlowRate{
			m.asUnit(pound) / float32(t.Minutes()),
			u,
		}, nil
	default:
		return *new(massFlowRate), errors.New(
			fmt.Sprintf("invalid massFlowRateUnit: '%v'", u))
	}
}

func (fr massFlowRate) asUnit(u massFlowRateUnit) float32 {
	kgps := fr.val * float32(fr.unit) // Convert to kilogramsPerSecond.
	return kgps / float32(u)          // Convert to desired unit.
}