--
-- Generic utility functions
--

-- Converts the number to an integer
int = math.floor

-- Tests if the given key is in the given lists key fields
function table.contains_key( table, key )
	for k,v in table do
		if k == key then return true end
	end
	return false
end

-- Tests if the given value is in the given lists value fields
function table.contains_value( table, value )
	for k,v in table do
		if v == value then return true end
	end
	return false
end

-- Maps the table via the given functions (applies the function to every value; the function is like "f(value,key)")
function table.map( table, func )
	local ret = {}
	local idx = 1

	for k,v in table do
		ret[ idx ] = func( v, k )
		idx = idx + 1
	end

	return ret
end

-- Clones the given table
function table.clone( table )
	local ret = {}
	for k,v in table do ret[ k ] = v end
	return ret
end

-- Joins the two tables (returns a new table). The second tables elements override the first tables elements.
function table.join( table1, table2 )
	local ret = table.clone( table1 )
	for k,v in table2 do ret[ k ] = v end
	return ret
end

-- Removes the given value from the table
function table.remove_value( table, value )
	for k,v in table do
		if v == value then
			table[ k ] = nil
			return
		end
	end
end

-- Inserts a value to a unique key to the table (the key is returned)
function table.insert_unique( table, value )
	local idx = 1
	while table[ idx ] ~= nil do idx = idx + 1 end
	table[ idx ] = value
	return idx
end

-- Returns the number of elements in the table
function table.size( table )
	local size = 0
	for k,v in table do size = size + 1 end
	return size
end
