Module:table/sparseArray

Ut Wikiwurdboek
local export = {}

local libraryUtil = require('libraryUtil')

local checkType = libraryUtil.checkType

function export.isPositiveInteger(v)
	if type(v) == 'number' and v >= 1 and math.floor(v) == v and v < math.huge then
		return true
	else
		return false
	end
end

function export.numKeys(t)
	checkType('numKeys', 1, t, 'table')
	local isPositiveInteger = export.isPositiveInteger
	local nums = {}
	for k, v in pairs(t) do
		if isPositiveInteger(k) then
			nums[#nums + 1] = k
		end
	end
	table.sort(nums)
	return nums
end

function export.compressSparseArray(t)
	checkType('compressSparseArray', 1, t, 'table')
	local ret = {}
	local nums = export.numKeys(t)
	for _, num in ipairs(nums) do
		ret[#ret + 1] = t[num]
	end
	return ret
end

return export