Last active
June 21, 2020 04:46
-
-
Save TannerRogalsky/8511136 to your computer and use it in GitHub Desktop.
A simple set implementation in lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local Set = {} | |
function Set.new() | |
local reverse = {} | |
local set = {} | |
return setmetatable(set, { | |
__index = { | |
insert = function(set, value) | |
if not reverse[value] then | |
table.insert(set, value) | |
reverse[value] = #set | |
end | |
end, | |
remove = function(set, value) | |
local index = reverse[value] | |
if index then | |
reverse[value] = nil | |
-- pop the top element off the set | |
local top = table.remove(set) | |
if top ~= value then | |
-- if it's not the element that we actually want to remove, | |
-- put it back into the set at the index of the element that we | |
-- do want to remove, replacing it | |
reverse[top] = index | |
set[index] = top | |
end | |
end | |
end, | |
contains = function(set, value) | |
return reverse[value] ~= nil | |
end | |
} | |
}) | |
end | |
return Set |
Thanks for making it!
awesome!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using it, seems to work nicely.