Skip to content

Instantly share code, notes, and snippets.

@skrolikowski
Last active December 10, 2020 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skrolikowski/8f9632ca97cac80df98a18add306f53a to your computer and use it in GitHub Desktop.
Save skrolikowski/8f9632ca97cac80df98a18add306f53a to your computer and use it in GitHub Desktop.
Item - a utility helper for Lua Tables (based on Laravel Collections)
-- Lua Table utility helper
-- Inspired by: https://laravel.com/docs/8.x/collections
Item = {}
Item.__index = Item
-- initializer
function Item:create(items)
assert(type(items) == 'table', 'Item expects a table.')
self.__index = self
return setmetatable({ items = items }, Item)
end
-- pretty print
function Item:__tostring()
local out = {}
for k, v in pairs(self.items) do
table.insert(out, string.format('%s=%s', k, v))
end
return '{ ' .. table.concat(out, ', ') .. ' }'
end
-- iterates through each item, sending it's
-- key and value through the given callback
function Item:map(cb)
for k, v in pairs(self.items) do
self.items[k] = cb(v, k)
end
return self
end
-- iterates though each item, filters out
-- non-truthy values returned by given callback
function Item:filter(cb)
for k, v in pairs(self.items) do
if not cb(v, k) then
self.items[k] = nil
end
end
return self
end
-- iterates though each item, filters out
-- truthy values returned by given callback
function Item:reject(cb)
for k, v in pairs(self.items) do
if cb(v, k) then
self.items[k] = nil
end
end
return self
end
-- merge new tbl into original table,
-- overriding existing values
function Item:merge(tbl)
if type(tbl) == 'table' then
for k, v in pairs(tbl) do
self.items[k] = v
end
end
return self
end
return Item
-- Usage example of Item class
--
local Item = require 'item'
-- helper function
function items(...)
return Item:create(...)
end
-- input
local tbl1 = { a = 1, b = 2, c = 3, d = 4, e = 5 }
local tbl2 -- updated
-- map, doubles every value
tbl2 = items(tbl):map(function(v, k)
return v * 2
end)
-- output
print(tbl2) -- { a=2, b=4, c=6, d=8, e=10 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment