But it is kind of messy so I made it a little bit better (It also has typechecking)
-- Filters a table based on a predicate function.
local function filter<K, V>(table : {[K]: V}, callback : (K, V) -> boolean) : {[K]: V}
local result = {}
for i, v in table do
if callback(i, v) then
result[i] = v
end
end
return result
end
And also the compare function
local function compare(x, ...)
return table.find({...}, x) ~= nil
end
It just simplifies your if statements so instead of doing this
if foo == bar and foo == baz and foo == qux then
-- ...
end
You can do this
if compare(foo, bar, baz, qux) then
-- ...
end
I know this isn’t a lot but I thought it would be helpful for some people so there you go
Creating an array just for comparisons then doing a table.find call doesn’t seem quite fast though, in alot of cases doing it the traditional way would be miles faster… And for filter, just don’t put in incorrect elements in the first place. But if your code doesn’t need to be fast and maybe you like js, this is a pretty solid post.
Heres a function I’d like to add which I use quite alot:
local function jumpTable<T..., R...>(cases: {[any | "_"]: (T...) -> (R...)}) -> (caseItem: any, T...) -> (R...)
return function(case, ...)
local handler = cases[case]
if handler then return handler(...) end
local default = cases._
if not default then return end
return default(...) -- Default case
end
end
It is essentially a switch statement; you can do this:
local jump = jumpTable {
Monday = function() print("It Is Monday") end,
Tuesday = function() print("It Is Tuesday") end,
_ = function() warn("Unknown day") end
}
jump("Monday")
jump("Saturday") -- Unknown day
It is quite nice for places where you have alot of possible values for something, makes it faster but also reduces overall nesting