Skip to content

Commit

Permalink
Runtime: Add table extensions for key and value retrieval
Browse files Browse the repository at this point in the history
Trivial stuff, but no point in recreating them again and again.
  • Loading branch information
rdw-software committed Feb 21, 2024
1 parent 26edf02 commit 93653ff
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Runtime/Extensions/tablex.lua
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ local ipairs = ipairs
local pairs = pairs
local type = type

local table_insert = table.insert

function table.contains(table, value)
validation.validateTable(table, "table")

Expand Down Expand Up @@ -77,5 +79,27 @@ function table.invert(tableToInvert)
return invertedTable
end

function table.keys(table)
validation.validateTable(table, "table")

local keys = {}
for key, value in pairs(table) do
table_insert(keys, key)
end

return keys
end

function table.values(table)
validation.validateTable(table, "table")

local values = {}
for key, value in pairs(table) do
table_insert(values, value)
end

return values
end

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

describe("keys", function()
it("should throw if a non-table value was passed as the first parameter", function()
assertThrows(function()
table.keys(nil)
end, "Expected argument table to be a table value, but received a nil value instead")
end)

it("should return a list of keys for both the array and the dictionary part of the given table", function()
local someTable = {
A = 42,
B = 123,
"Hello",
"world",
}
local keys = table.keys(someTable)
assertTrue(table.contains(keys, 1))
assertTrue(table.contains(keys, 2))
assertTrue(table.contains(keys, "A"))
assertTrue(table.contains(keys, "B"))
end)
end)

describe("values", function()
it("should throw if a non-table value was passed as the first parameter", function()
assertThrows(function()
table.values(nil)
end, "Expected argument table to be a table value, but received a nil value instead")
end)

it("should return a list of values for both the array and the dictionary part of the given table", function()
local someTable = {
A = 42,
B = 123,
"Hello",
"world",
}
local values = table.values(someTable)
assertTrue(table.contains(values, 42))
assertTrue(table.contains(values, 123))
assertTrue(table.contains(values, "Hello"))
assertTrue(table.contains(values, "world"))
end)
end)
end)

0 comments on commit 93653ff

Please sign in to comment.