From 2ecc8cb2d7787a2f211fb6726f1aff02ecdd8f20 Mon Sep 17 00:00:00 2001 From: Starbeamrainbowlabs Date: Sat, 21 Jan 2023 02:32:09 +0000 Subject: [PATCH] add implementation of array.reduce() from JS --- worldeditadditions_core/utils/table/init.lua | 1 + .../utils/table/table_reduce.lua | 13 +++++++++++++ 2 files changed, 14 insertions(+) create mode 100644 worldeditadditions_core/utils/table/table_reduce.lua diff --git a/worldeditadditions_core/utils/table/init.lua b/worldeditadditions_core/utils/table/init.lua index 177dfdf..f09829b 100644 --- a/worldeditadditions_core/utils/table/init.lua +++ b/worldeditadditions_core/utils/table/init.lua @@ -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"), diff --git a/worldeditadditions_core/utils/table/table_reduce.lua b/worldeditadditions_core/utils/table/table_reduce.lua new file mode 100644 index 0000000..2d2bbca --- /dev/null +++ b/worldeditadditions_core/utils/table/table_reduce.lua @@ -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 \ No newline at end of file