Skip to content

Commit

Permalink
BAAS-18673: add support for float in Sets (#111)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabri3l authored Jan 12, 2024
1 parent 2eb6675 commit ece6fc6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
14 changes: 14 additions & 0 deletions builtin_set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,17 @@ 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);
const doesNotHaveFloat = s.has(1.3);
s.add(2.0)
const hasInt = s.has(2)
hasFloat && hasInt && !doesNotHaveFloat`

testScript(SCRIPT, valueTrue, t)
}
20 changes: 20 additions & 0 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,11 +24,30 @@ 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 {
}
return
Expand Down

0 comments on commit ece6fc6

Please sign in to comment.