Skip to content

Commit

Permalink
split isIntegralNumber func
Browse files Browse the repository at this point in the history
  • Loading branch information
syumai committed Feb 26, 2023
1 parent 53627e7 commit a496d2d
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
13 changes: 11 additions & 2 deletions cloudflare/d1/rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ func (r *rows) Close() error {
return nil
}

// isIntegralNumber returns if given float64 value is integral value or not.
func isIntegralNumber(f float64) bool {
// If the value is NaN or Inf, returns the value to avoid being mistakenly treated as an integral value.
if math.IsNaN(f) || math.IsInf(f, 0) {
return false
}
return f == math.Trunc(f)
}

// convertRowColumnValueToDriverValue converts row column's value in JS to Go's driver.Value.
// row column value is `null | Number | String | ArrayBuffer`.
// see: https://developers.cloudflare.com/d1/platform/client-api/#type-conversion
Expand All @@ -60,8 +69,8 @@ func convertRowColumnValueToAny(v js.Value) (driver.Value, error) {
return nil, nil
case js.TypeNumber:
fv := v.Float()
// if the value can be treated as integer, return as int64.
if fv == math.Trunc(fv) {
// if the value can be treated as integral value, return as int64.
if isIntegralNumber(fv) {
return int64(fv), nil
}
return fv, nil
Expand Down
44 changes: 44 additions & 0 deletions cloudflare/d1/rows_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package d1

import (
"math"
"testing"
)

func Test_isIntegralNumber(t *testing.T) {
tests := map[string]struct {
f float64
want bool
}{
"valid integral value": {
f: 1,
want: true,
},
"invalid float value": {
f: 1.1,
want: false,
},
"invalid NaN": {
f: math.NaN(),
want: false,
},
"invalid +Inf": {
f: math.Inf(+1),
want: false,
},
"invalid -Inf": {
f: math.Inf(-1),
want: false,
},
}
for name, tc := range tests {
name := name
tc := tc
t.Run(name, func(t *testing.T) {
t.Parallel()
if got := isIntegralNumber(tc.f); got != tc.want {
t.Errorf("isIntegralNumber() = %v, want %v", got, tc.want)
}
})
}
}

0 comments on commit a496d2d

Please sign in to comment.