Skip to content

Commit

Permalink
feat(tablefunctions): let table.map callback modify keys (#3487)
Browse files Browse the repository at this point in the history
If the callback passes a second return value, that will be used as the
new key. The caller is responsible for avoiding collisions.
  • Loading branch information
salinecitrine authored Sep 5, 2024
1 parent 87b267d commit d2ff9fd
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions common/tablefunctions.lua
Original file line number Diff line number Diff line change
Expand Up @@ -310,14 +310,19 @@ end

if not table.map then
--- Applies a function to all elements of a table and returns a new table with the results.
---@generic K, V, R
---@generic K, V, RV, RK
---@param tbl table<K, V> The input table.
---@param callback fun(value: V, key: K, tbl: table<K, V>): R The function to apply to each element. It receives three arguments: the element's value, its key, and the original table.
---@return R[] A new table containing the results of applying the callback to each element.
---@param callback fun(value: V, key: K, tbl: table<K, V>): RV, RK The function to apply to each element. It receives three arguments: the element's value, its key, and the original table. It should return the new value, and optionally, a new key.
---@return table<RK, RV> A new table containing the results of applying the callback to each element.
function table.map(tbl, callback)
local result = {}
for k, v in pairs(tbl) do
result[k] = callback(v, k, tbl)
local mappedValue, mappedKey = callback(v, k, tbl)
if mappedKey ~= nil then
result[mappedKey] = mappedValue
else
result[k] = mappedValue
end
end
return result
end
Expand Down

0 comments on commit d2ff9fd

Please sign in to comment.