Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a new table.invert standard library extension #508

Merged
merged 1 commit into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Loading