tablex: Skip equality comparison in equal fn

The second loop doesn't care if the values are equal. It only checks if
the keys are there. The first loop already checked for equality.

Add tests to prove correctness using testy.lua.
This commit is contained in:
David Briscoe 2022-03-02 08:11:30 -08:00
parent f6a18380d4
commit 5b4d1c16c5
2 changed files with 50 additions and 2 deletions

View File

@ -417,8 +417,9 @@ function tablex.shallow_equal(a, b)
return false return false
end end
end end
-- second loop to ensure a isn't missing any keys from b.
for k, v in pairs(b) do for k, v in pairs(b) do
if a[k] ~= v then if a[k] == nil then
return false return false
end end
end end
@ -442,8 +443,10 @@ function tablex.deep_equal(a, b)
return false return false
end end
end end
-- second loop to ensure a isn't missing any keys from b, so we can skip
-- recursion.
for k, v in pairs(b) do for k, v in pairs(b) do
if not tablex.deep_equal(v, a[k]) then if a[k] == nil then
return false return false
end end
end end

45
tests.lua Normal file
View File

@ -0,0 +1,45 @@
-- Run this file with testy:
-- testy.lua tests.lua
-- testy sets `...` to "module.test", so ignore that and use module top-level paths.
package.path = package.path .. ";../?.lua"
local assert = require("batteries.assert")
local tablex = require("batteries.tablex")
-- tablex {{{
local function test_shallow_equal()
local x,y
x = { a = { b = { 2 }, } }
y = { a = { b = { 2 }, } }
assert(not tablex.shallow_equal(x, y))
x = { 3, 4, "hello", [20] = "end", }
y = { 3, 4, "hello", [20] = "end", }
assert(tablex.shallow_equal(x, y))
local z = { 1, 2, }
x = { a = z, b = 10, c = true, }
y = { a = z, b = 10, c = true, }
assert(tablex.shallow_equal(x, y))
assert(tablex.shallow_equal(y, x))
end
local function test_deep_equal()
local x,y
x = { a = { b = { 2 }, c = { 3 }, } }
y = { a = { b = { 2 }, c = { 3 }, } }
assert(tablex.deep_equal(x, y))
x = { a = { b = { 1, 2 }, c = { 3 }, } }
y = { a = { c = { 3 }, b = { [2] = 2, [1] = 1 }, } }
assert(tablex.deep_equal(x, y))
assert(tablex.deep_equal(y, x))
x = { a = { b = { 2 }, c = { 3 }, 2 } }
y = { a = { b = { 2 }, c = { 3 }, } }
assert(not tablex.deep_equal(x, y))
assert(not tablex.deep_equal(y, x))
end