Browse Source

Code cleanup..

replace multi if block with a switch statement
  clean up comments
master
jimi 9 years ago
parent
commit
caf80cb747
  1. 40
      triangle.go

40
triangle.go

@ -1,14 +1,14 @@
// Package triangle determines what kind of triangle three side lengths make.
// Package triangle: Determine what kind of triangle three side lengths make.
package triangle
import "math"
// An enumeration of triangle types
const (
NaT Kind = iota
Equ
Iso
Sca
NaT Kind = iota // Not a triangle
Equ // Equlateral
Iso // Isometric
Sca // Scalene
testVersion = 2
)
@ -18,31 +18,29 @@ type Kind int
// KindFromSides determines whether the three side lengths given
// constitute a triangle and if so, what type of triangle it is.
func KindFromSides(a, b, c float64) Kind {
func KindFromSides(a, b, c float64) (k Kind) {
// Return NaT when any side is zero, negative, infinite, or NaN.
for _, f := range []float64{a, b, c} {
if f <= 0 || f != f || math.IsInf(f, 0) {
return NaT
}
}
switch {
// Return NaT if the sides fail triangle inequality tests.
if a+b < c || b+c < a || a+c < b {
return NaT
case a+b < c || b+c < a || a+c < b:
k = NaT
case a == b && b == c: // 3 equal length sides (Equ)
k = Equ
case a == b || b == c || a == c: // 2 equal length sides (Iso)
k = Iso
case a != b || b != c || a != c: // No equal length sides (Sca)
k = Sca
}
if a == b && b == c {
return Equ
}
if a == b || b == c || a == c {
return Iso
}
if a != b || b != c || a != c {
return Sca
}
return NaT
return k
}
// Iteration 1 benkmark results:
// Iteration 2 benkmark results:
//
// PASS
// BenchmarkKind-12 2000000 643 ns/op
// ok exercism/go/triangle 1.948s
// BenchmarkKind-12 2000000 651 ns/op
//
Loading…
Cancel
Save