Skip to content

Commit

Permalink
BAAS-24348: Add proper handling of float values in sets
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabri3l committed Jan 12, 2024
1 parent 4430dc8 commit 15b890a
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
13 changes: 13 additions & 0 deletions builtin_set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,16 @@ func TestSetGetAdderGetIteratorOrder(t *testing.T) {
`
testScript(SCRIPT, valueTrue, t)
}

func TestSetHasFloatVsInt(t *testing.T) {
const SCRIPT = `const s = new Set()
s.add(1);
const hasFloat = s.has(1.0);
s.add(2.0)
const hasInt = s.has(2)
hasFloat && hasInt`

testScript(SCRIPT, valueTrue, t)
}
40 changes: 38 additions & 2 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package goja

import (
"hash/maphash"
"math"
)

type mapEntry struct {
Expand All @@ -23,14 +24,49 @@ type orderedMapIter struct {
cur *mapEntry
}

func convertFloatToInt(f valueFloat) (valueInt, bool) {
if f == valueFloat(math.Trunc(float64(f))) {
return valueInt(f), true
}
return 0, false
}

func (m *orderedMap) lookup(key Value) (h uint64, entry, hPrev *mapEntry) {
if key == _negativeZero {
key = intToValue(0)
}

switch t := key.(type) {
case valueFloat:
// If a float can be converted to an integer without data loss
// we should be able to convert to integer. This will allow Sets
// to find floats accordingly. Doing mySet.has(1.0) for a set that
// has 1 in it, should return true.
if intValue, ok := convertFloatToInt(t); ok {
key = intValue
}
}
h = key.hash(m.hash)
for entry = m.hashTable[h]; entry != nil && !entry.key.SameAs(key); hPrev, entry = entry, entry.hNext {

entry = m.hashTable[h]
for {
if entry == nil {
return
}

src := entry.key
switch t := entry.key.(type) {
case valueInt:
src = floatToValue(t.ToFloat())
case valueInt64:
src = floatToValue(t.ToFloat())
}
if src.SameAs(key) {
return
}

hPrev, entry = entry, entry.hNext
}
return
}

func (m *orderedMap) set(key, value Value) {
Expand Down

0 comments on commit 15b890a

Please sign in to comment.