Skip to content
Open
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
8 changes: 8 additions & 0 deletions lute/std/libs/tableext.luau
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ function tableext.keys<K, V>(tbl: { [K]: V }): { K }
return keys
end

function tableext.toset<T>(tbl: { T }): { [T]: true }
local set: { [T]: true } = {}
for _, v in tbl do
set[v] = true
end
return set
end

function tableext.reverse<T>(tbl: { T }, inplace: boolean?)
local new = if inplace then tbl else {}
local i, j = 1, #tbl
Expand Down
33 changes: 33 additions & 0 deletions tests/std/tableext.test.luau
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,39 @@ test.suite("TableExt", function(suite)
assert.tableeq(b, { 4, 5, 6 })
assert.tableeq(c, { 6, 5, 4 })
end)

suite:case("toset", function(assert)
local a = { 1, 2, 4, 2, 1 }
local setA = tableext.toset(a)
assert.eq(setA[1], true)
assert.eq(setA[2], true)
assert.eq(setA[3], nil)
assert.eq(setA[4], true)
assert.eq(setA[5], nil)

local setSize = #tableext.keys(setA)
assert.eq(setSize, 3)
assert.neq(setSize, #a)

local foundKeys: { number } = {}
for key, value in setA do
assert.eq(value, true)
table.insert(foundKeys, key)
end
assert.eq(#foundKeys, setSize)
assert.eq(setA[foundKeys[1]], true)
assert.eq(setA[foundKeys[2]], true)
assert.eq(setA[foundKeys[3]], true)
Comment on lines +79 to +87
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sanity check to verify that sets created using an array of numbers doesn't break from having gaps between the number keys.

This repo seems to avoid comments where possible so I left this comment out of code but can add if you think it's appropriate.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can author comments that explain why things are the way they are. There's no desire or commitment to avoiding comments in general, though I would probably tell people to omit comments that are just a direct explanation of the code that immediately follows it since those kinds of comments get stale all the time and add very little value. Explanations of why are great, high-level descriptions of overarching decisions that affect everything that follows are great, etc.


local b = { "a", "b", "c", "a" }
local setB = tableext.toset(b)
assert.eq(setB["a"], true)
assert.eq(setB["b"], true)
assert.eq(setB["c"], true)
assert.eq(setB["d"], nil)
assert.eq(#tableext.keys(setB), 3)
assert.neq(#tableext.keys(setB), #b)
end)
end)

test.run()