Pergi ke kandungan

Modul:languages/print

Daripada Wikikamus
local export = {}

local function for_code_and_data(func)
	function iterate(module)
		for code, data in pairs(require("Module:languages/" .. module)) do
			func(code, data)
		end
	end
	
	iterate("data/2")
	
	local char = string.char
	for b = ("a"):byte(), ("z"):byte() do
		iterate("data/3/" .. char(b))
	end
	
	iterate("data/exceptional")
end

local function generate_table(name_to_code)
	local result = {}
	
	if name_to_code then
		for_code_and_data(function(code, data) result[data[1]] = code end)
	else
		for_code_and_data(function(code, data) result[code] = data[1] end)
	end
	
	return result
end

local function dump(data, name_to_code)
	local output = { "return {" }
	local i = 1
	local sorted_pairs = require "Module:table".sortedPairs
	
	for k, v in sorted_pairs(data) do
		i = i + 1
		output[i] = ('\t[%q] = %q,'):format(k, v)
	end
	
	table.insert(output, "}")
	
	return table.concat(output, "\n")
end

local function print_data(name_to_code, args)
	if args[1] == "plain" then
		return dump(generate_table(name_to_code), name_to_code)
	elseif args[1] == "json" then
		return require "Module:JSON/minified".toJSON(generate_table(name_to_code), { sort_keys = true })
	else
		return require "Module:debug".highlight(dump(generate_table(name_to_code), name_to_code))
	end
end

function export.code_to_name(frame)
	return print_data(false, frame.args)
end

function export.name_to_code(frame)
	return print_data(true, frame.args)
end

function export.appendix_constructed_canonical_names(frame)
	local names = {}
	for_code_and_data(function(code, data)
		if data.type == "appendix-constructed" then
			table.insert(names, data[1])
		end
	end)
	table.sort(names)
	return mw.text.jsonEncode(names)
end

return export