add implementation of array.reduce() from JS

This commit is contained in:
Starbeamrainbowlabs 2023-01-21 02:32:09 +00:00
parent 66227153d0
commit 2ecc8cb2d7
Signed by: sbrl
GPG key ID: 1BE5172E637709C2
2 changed files with 14 additions and 0 deletions

View file

@ -18,6 +18,7 @@ wea_c.table = {
get_last = dofile(wea_c.modpath.."/utils/table/table_get_last.lua"),
makeset = dofile(wea_c.modpath.."/utils/table/makeset.lua"),
map = dofile(wea_c.modpath.."/utils/table/table_map.lua"),
reduce = dofile(wea_c.modpath.."/utils/table/table_reduce.lua"),
shallowcopy = dofile(wea_c.modpath.."/utils/table/shallowcopy.lua"),
tostring = dofile(wea_c.modpath.."/utils/table/table_tostring.lua"),
unique = dofile(wea_c.modpath.."/utils/table/table_unique.lua"),

View file

@ -0,0 +1,13 @@
--- Lua implementation of array.reduce() from Javascript.
-- @param tbl The table to iterate over.
-- @param func The function to call for every element in tbl. Will be passed the following arguments: accumulator, value, index, table. Of course, the provided function need not take this many arguments.
-- @param initial_value The initial value of the accumulator.
local function table_reduce(tbl, func, initial_value)
local acc = initial_value
for key, value in pairs(tbl) do
acc = func(acc, value, key, tbl)
end
return acc
end