Skip to content

Commit 3a4ba23

Browse files
Merge pull request #100 from gburt/main
Fix some comparisons
2 parents cfec081 + 50fc348 commit 3a4ba23

File tree

5 files changed

+635
-37
lines changed

5 files changed

+635
-37
lines changed

comp.go

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"math"
55
"reflect"
66
"strconv"
7+
"strings"
78
)
89

910
// at simulate undefined in javascript
@@ -31,6 +32,10 @@ func toNumberForLess(v any) float64 {
3132
return 0
3233
}
3334
case string:
35+
if strings.TrimSpace(value) == "" {
36+
return 0
37+
}
38+
3439
n, err := strconv.ParseFloat(value, 64)
3540
switch err {
3641
case strconv.ErrRange, nil:
@@ -74,15 +79,12 @@ func equals(a, b any) bool {
7479
return a == b
7580
}
7681

77-
if isNumber(a) {
78-
return isPrimitive(b) && toNumber(a) == toNumber(b)
82+
if isPrimitive(a) && isPrimitive(b) && (isNumber(a) || isNumber(b)) {
83+
return toNumberForLess(a) == toNumberForLess(b)
7984
}
8085

81-
if isBool(a) {
82-
if !isBool(b) {
83-
return false
84-
}
85-
return isTrue(a) == isTrue(b)
86+
if isBool(a) || isBool(b) {
87+
return isTruthy(a) == isTruthy(b)
8688
}
8789

8890
if !isString(a) || !isString(b) {
@@ -91,3 +93,11 @@ func equals(a, b any) bool {
9193

9294
return toString(a) == toString(b)
9395
}
96+
97+
func isTruthy(v any) bool {
98+
return toNumberForLess(v) == 1
99+
}
100+
101+
func isFalsey(v any) bool {
102+
return toNumberForLess(v) == 0
103+
}

comp_test.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,8 @@ func TestEqualsWithBooleans(t *testing.T) {
6767
func TestEqualsWithNil(t *testing.T) {
6868
assert.True(t, equals(nil, nil))
6969
assert.False(t, equals(nil, ""))
70-
}
70+
}
71+
72+
func TestEqualsWithNumberAndString(t *testing.T) {
73+
assert.True(t, equals("1", 1))
74+
}

0 commit comments

Comments
 (0)