mirror of
https://github.com/syumai/workers.git
synced 2025-03-10 17:29:11 +00:00
split isIntegralNumber func
This commit is contained in:
parent
53627e79e8
commit
a496d2d714
@ -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
|
||||
@ -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
|
||||
|
44
cloudflare/d1/rows_test.go
Normal file
44
cloudflare/d1/rows_test.go
Normal file
@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user