Module:table/sparseArray

From Wiktionary, the free dictionary
Jump to navigation Jump to search
This module needs documentation.
Please document this module by describing its purpose and usage on the documentation page.

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