Commits

Eric Roshan Eisner  committed 934b72f Draft

support compound units in unit parser

  • Participants
  • Parent commits 8701238

Comments (0)

Files changed (2)

 	delete(namedUnits, "kL")
 }
 
-func parseUnit(s string) (v Value, ok bool) {
+func parseSimpleUnit(s string) (v Value, ok bool) {
 	// get the longest valid suffix as the base unit
 	i := 0
 	for ; i < len(s); i++ {
 	}
 	return v, true
 }
+
+func parseUnit(s string) (v Value, ok bool) {
+	v.num = 1
+	v.units = Unitless
+	start := 0
+	numerator := true
+	for i := 0; i <= len(s); i++ {
+		if i == len(s) || s[i] == '/' || s[i] == '*' {
+			val, ok := parseSimpleUnit(s[start:i])
+			if !ok {
+				return Value{}, false
+			}
+			if numerator {
+				v = v.Mul(val)
+			} else {
+				v = v.Div(val)
+			}
+			start = i + 1
+		}
+		if i < len(s) && s[i] == '/' {
+			numerator = !numerator
+		}
+	}
+	return v, true
+}

File parse_test.go

 	{"uin", "25.4nm", true},
 	{"kg", "1kg", true},
 	{"ml", "1mL", true},
+
+	{"m//s", "0", false},
+	{"m/s/", "0", false},
+	{"*m/s", "0", false},
+	{"m/s", "1m/s", true},
+	{"kg*m/s*s", "1N", true},
 }
 
 func TestParseUnit(t *testing.T) {