--- ACF2 utility functions.
--
-- @module acf2.util

--[[
Copyright (c) 2012-2013 Kaarle Ritvanen
See LICENSE file for license details
--]]


local M = {}

--- set default value for a key in a table unless it is already set.
-- @param t the table
-- @param k the key
-- @param v the default value
-- @return the value `t[k]`
function M.setdefault(t, k, v)
   if t[k] == nil then t[k] = v end
   return t[k]
end

--- merge a table into another.
-- Copy values for all keys from `src` to `dst` and optionally keep existing
-- values.
-- @param dst the destination table
-- @param src the source table
-- @param preserve a boolean. If true then will existing entries in `dst` be
-- kept.
-- @return the destination table, `dst`
function M.update(dst, src, preserve)
   for k, v in pairs(src) do
      if not preserve or dst[k] == nil then dst[k] = v end
   end
   return dst
end

--- copy default vaules from one table to another.
-- Copy all entries in `src` to `dst` but keep any already existing values
-- in `dst`.
-- @param dst the destination table
-- @param src the source table containing the default values
-- @return the destination table, `dst`
function M.setdefaults(dst, src) return M.update(dst, src, true) end

--- copy a varable.
-- If `var` is a table, then the table is cloned, otherwise return the value
-- of `var`.
-- @param var the variable to copy
-- @return a clone of `var`
function M.copy(var)
   return type(var) == 'table' and M.setdefaults({}, var) or var
end

--- extend an array.
-- inserts all elements in `src` into `dst`
-- @param dst the destination array
-- @param src the source array
-- @return the destination array, `dst`
function M.extend(dst, src)
   for _, v in ipairs(src) do table.insert(dst, v) end
   return dst
end

--- extract the keys of a table as an array.
-- @param tbl a table
-- @return an array of keys
function M.keys(tbl)
   local res = {}
   for k, v in pairs(tbl) do table.insert(res, k) end
   return res
end

--- map a function over a table.
-- @param func a function with one argument
-- @param tbl the table
-- @return the transformed table
function M.map(func, tbl)
   local res = {}
   for k, v in pairs(tbl) do res[k] = func(v) end
   return res
end

return M
