MithrilJS / ospec

Noiseless testing framework
MIT License
48 stars 13 forks source link

DeepEquals should handle Sets (and Maps) #66

Open pygy opened 9 months ago

pygy commented 9 months ago

For sets, this does an object identity check for membership, I suppose we could do N^2 deepEqual() checks on the set members to determine if they match... Likewise for maps...

      if (a instanceof Set && b instanceof Set) {
        for (const el of a) {
          if (!b.has(el)) return false
        }
        for (const el of b) {
          if (!a.has(el)) return false
        }
        return true
      }
dead-claudia commented 8 months ago

You don't need to check both sets. Just assert the size. If sizes are equal and all keys of a are contained in b, you have equal sets.

if (a.size !== b.size) return false
for (const key of a) {
    if (!b.has(key)) return false
}
return true

The proof is relatively straightforward:


Edit: the same goes for maps. Proof is similar.

if (a.size !== b.size) return false
for (const [key, value] of a) {
    if (!b.has(key)) return false
    if (!deepEqual(value, b.get(key)) return false
}
return true