Add func.iterate and func.aggregate

master
Lars Mueller 2021-07-03 11:55:36 +02:00
parent eb2db70201
commit 7a82efb75f
2 changed files with 36 additions and 0 deletions

View File

@ -34,6 +34,31 @@ function values(...)
return function() return unpack(args) end
end
-- Equivalent to `for x, y, z in iterator(...) do callback(x, y, z) end`
function iterate(callback, iterator, ...)
local function _iterate(iterable, state, ...)
local function loop(...)
if ... == nil then return end
callback(...)
return loop(iterable(state, ...))
end
return loop(iterable(state, ...))
end
return _iterate(iterator(...))
end
-- Does not use select magic, stops at the first nil value
function aggregate(binary_func, total, ...)
if total == nil then return end
local function _aggregate(value, ...)
if value == nil then return end
total = binary_func(total, value)
return _aggregate(...)
end
_aggregate(...)
return total
end
function override_chain(func, override)
return function(...)
func(...)

View File

@ -16,6 +16,17 @@ setfenv(1, setmetatable({}, {
end
}))
-- func
do
local tab = {a = 1, b = 2}
func.iterate(function(key, value)
assert(tab[key] == value)
tab[key] = nil
end, pairs, tab)
assert(next(tab) == nil)
assert(func.aggregate(func.add, 1, 2, 3) == 6)
end
-- string
assert(string.escape_magic_chars"%" == "%%")