--- Alpine Configurator utility functions.
--
-- @module aconf.util

--[[
Copyright (c) 2012-2015 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. A new table is created if `dst` is nil.
-- @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)
   if not dst then dst = {} end
   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`. A new table is created if `dst` is nil.
-- @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

--- determine whether a value is present in an array.
-- @param list an array
-- @param value a value
-- @return a boolean
function M.contains(list, value)
   for k, v in ipairs(list) do if v == value then return true end end
   return false
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

--- select array values satisfying a filter.
-- @param func a function with one argument
-- @param list the array
-- @return the filtered array
function M.filter(func, list)
   local res = {}
   for _, v in ipairs(list) do if func(v) then table.insert(res, v) end end
   return res
end

return M
