Skip to content

Commit 76dc811

Browse files
artem-sidorenkobep
authored andcommitted
tpl/math: Refactor Mod with cast
It makes the code smaller
1 parent 488631f commit 76dc811

File tree

2 files changed

+18
-20
lines changed

2 files changed

+18
-20
lines changed

‎tpl/math/math.go‎

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -72,21 +72,10 @@ func (ns *Namespace) Log(a interface{}) (float64, error) {
7272

7373
// Mod returns a % b.
7474
func (ns *Namespace) Mod(a, b interface{}) (int64, error) {
75-
av := reflect.ValueOf(a)
76-
bv := reflect.ValueOf(b)
77-
var ai, bi int64
78-
79-
switch av.Kind() {
80-
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
81-
ai = av.Int()
82-
default:
83-
return 0, errors.New("Modulo operator can't be used with non integer value")
84-
}
75+
ai, erra := cast.ToInt64E(a)
76+
bi, errb := cast.ToInt64E(b)
8577

86-
switch bv.Kind() {
87-
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
88-
bi = bv.Int()
89-
default:
78+
if erra != nil || errb != nil {
9079
return 0, errors.New("Modulo operator can't be used with non integer value")
9180
}
9281

‎tpl/math/math_test.go‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -259,13 +259,17 @@ func TestMod(t *testing.T) {
259259
{3, 1, int64(0)},
260260
{3, 0, false},
261261
{0, 3, int64(0)},
262-
{3.1, 2, false},
263-
{3, 2.1, false},
264-
{3.1, 2.1, false},
262+
{3.1, 2, int64(1)},
263+
{3, 2.1, int64(1)},
264+
{3.1, 2.1, int64(1)},
265265
{int8(3), int8(2), int64(1)},
266266
{int16(3), int16(2), int64(1)},
267267
{int32(3), int32(2), int64(1)},
268268
{int64(3), int64(2), int64(1)},
269+
{"3", "2", int64(1)},
270+
{"3.1", "2", false},
271+
{"aaa", "0", false},
272+
{"3", "aaa", false},
269273
} {
270274
errMsg := fmt.Sprintf("[%d] %v", i, test)
271275

@@ -296,9 +300,9 @@ func TestModBool(t *testing.T) {
296300
{3, 1, true},
297301
{3, 0, nil},
298302
{0, 3, true},
299-
{3.1, 2, nil},
300-
{3, 2.1, nil},
301-
{3.1, 2.1, nil},
303+
{3.1, 2, false},
304+
{3, 2.1, false},
305+
{3.1, 2.1, false},
302306
{int8(3), int8(3), true},
303307
{int8(3), int8(2), false},
304308
{int16(3), int16(3), true},
@@ -307,6 +311,11 @@ func TestModBool(t *testing.T) {
307311
{int32(3), int32(2), false},
308312
{int64(3), int64(3), true},
309313
{int64(3), int64(2), false},
314+
{"3", "3", true},
315+
{"3", "2", false},
316+
{"3.1", "2", nil},
317+
{"aaa", "0", nil},
318+
{"3", "aaa", nil},
310319
} {
311320
errMsg := fmt.Sprintf("[%d] %v", i, test)
312321

0 commit comments

Comments
 (0)