mirror of
https://github.com/tendermint/tendermint.git
synced 2026-01-03 03:35:19 +00:00
light cli: add feature flags and save providers (#5148)
This commit is contained in:
@@ -1,6 +1,11 @@
|
||||
package math
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Fraction defined in terms of a numerator divided by a denominator in int64
|
||||
// format.
|
||||
@@ -15,3 +20,23 @@ type Fraction struct {
|
||||
func (fr Fraction) String() string {
|
||||
return fmt.Sprintf("%d/%d", fr.Numerator, fr.Denominator)
|
||||
}
|
||||
|
||||
// ParseFractions takes the string of a fraction as input i.e "2/3" and converts this
|
||||
// to the equivalent fraction else returns an error. The format of the string must be
|
||||
// one number followed by a slash (/) and then the other number.
|
||||
func ParseFraction(f string) (Fraction, error) {
|
||||
o := strings.SplitN(f, "/", -1)
|
||||
if len(o) != 2 {
|
||||
return Fraction{}, errors.New("incorrect formating: should be like \"1/3\"")
|
||||
}
|
||||
numerator, err := strconv.ParseInt(o[0], 10, 64)
|
||||
if err != nil {
|
||||
return Fraction{}, fmt.Errorf("incorrect formatting, err: %w", err)
|
||||
}
|
||||
|
||||
denominator, err := strconv.ParseInt(o[1], 10, 64)
|
||||
if err != nil {
|
||||
return Fraction{}, fmt.Errorf("incorrect formatting, err: %w", err)
|
||||
}
|
||||
return Fraction{Numerator: numerator, Denominator: denominator}, nil
|
||||
}
|
||||
|
||||
68
libs/math/fraction_test.go
Normal file
68
libs/math/fraction_test.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package math
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestParseFraction(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
f string
|
||||
exp Fraction
|
||||
err bool
|
||||
}{
|
||||
{
|
||||
f: "2/3",
|
||||
exp: Fraction{2, 3},
|
||||
err: false,
|
||||
},
|
||||
{
|
||||
f: "15/5",
|
||||
exp: Fraction{15, 5},
|
||||
err: false,
|
||||
},
|
||||
{
|
||||
f: "-1/2",
|
||||
exp: Fraction{-1, 2},
|
||||
err: false,
|
||||
},
|
||||
{
|
||||
f: "1/-2",
|
||||
exp: Fraction{1, -2},
|
||||
err: false,
|
||||
},
|
||||
{
|
||||
f: "2/3/4",
|
||||
exp: Fraction{},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
f: "123",
|
||||
exp: Fraction{},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
f: "1a2/4",
|
||||
exp: Fraction{},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
f: "1/3bc4",
|
||||
exp: Fraction{},
|
||||
err: true,
|
||||
},
|
||||
}
|
||||
|
||||
for idx, tc := range testCases {
|
||||
output, err := ParseFraction(tc.f)
|
||||
if tc.err {
|
||||
assert.Error(t, err, idx)
|
||||
} else {
|
||||
assert.NoError(t, err, idx)
|
||||
}
|
||||
assert.Equal(t, tc.exp, output, idx)
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user