Skip to content

Commit

Permalink
Merge pull request #508 from evo-lua/table-invert-builtin
Browse files Browse the repository at this point in the history
Add a new table.invert standard library extension
  • Loading branch information
rdw-software authored Feb 19, 2024
2 parents c5cf4cf + c906f38 commit 3d270e8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Runtime/Extensions/tablex.lua
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,16 @@ function table.reverse(tableToReverse)
return reversedTable
end

function table.invert(tableToInvert)
validation.validateTable(tableToInvert, "tableToInvert")

local invertedTable = {}
for key, value in pairs(tableToInvert) do
invertedTable[value] = key
end

return invertedTable
end

table.clear = require("table.clear")
table.new = require("table.new")
14 changes: 14 additions & 0 deletions Tests/BDD/table-library.spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,18 @@ describe("table", function()
assertEquals(table.reverse(input), expectedOutput)
end)
end)

describe("invert", function()
it("should throw if a non-table value was passed", function()
assertThrows(function()
table.invert(42)
end, "Expected argument tableToInvert to be a table value, but received a number value instead")
end)

it("should return a copy of the table with the keys and values swapped", function()
local input = { "A", "B", "C" }
local expectedOutput = { A = 1, B = 2, C = 3 }
assertEquals(table.invert(input), expectedOutput)
end)
end)
end)

0 comments on commit 3d270e8

Please sign in to comment.