Module:Array

From MTG Wiki
Jump to navigation Jump to search

Documentation for this module may be created at Module:Array/doc

local p = {}
local lib = require('Module:Feature')

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame, {
		parentFirst = true,
		wrapper = { 'Template:Array' }
	})
	return p._main(args, frame)
end

function p._removeDuplicates(arr)
	local hash = {}
	local res = {}

	for _,v in ipairs(arr) do
	   if (not hash[v]) then
	       res[#res+1] = v
	       hash[v] = true
	   end
	end

	return res
end

function p._main(args, frame)
	local arrayString = args[1] or nil
	local separator = args[2] or nil
	local format = args[3] or nil
	local join = args[4] or ""
	local dedupe = args["dedupe"] or nil

	-- argument validation
	if arrayString == nil then return error("First argument (arrayString) must not be empty.") end
	if separator == nil then return error("Second argument (separator) must not be empty.") end
	if separator == "" then return error("Second argument (separator) must not be empty string.") end
	if format == nil then return error("Third argument (format) must not be empty.") end
	if format:find("{item}") == nil then return error("Third argument (format) does not include {item}.") end

	-- split string
	local array = lib.split(arrayString, separator)

	if dedupe == "1" then
		array = p._removeDuplicates(array)
	end

	-- create result
	local result = ""
	for key, value in pairs(array) do
		local item = format
		item = item:gsub("{item}", value)
		item = item:gsub("{newline}", "\n")
		item = item:gsub("{index}", key)
		array[key] = item
	end
	mw.logObject(array)
	result = table.concat(array, join)
	return result
end

return p