Module:th-anagram

Text-x-generic with pencil.svg This module needs documentation.
Please document this module by describing its purpose and usage on the documentation page.

local export = {}

local links = require("Module:links")

local lang = require("Module:languages").getByCode("th")
local script = require("Module:scripts").getByCode("Thai")
local PAGENAME = mw.title.getCurrentTitle().text

local function contains(table, val)

	for i = 1, #table do
		if table[i] == val then 
			return true
		end
	end

	return false

end

local function hash(text)

	local charTbl = {}

	-- Some symbols added for unmatching.
	for c in mw.ustring.gmatch(text, "[ก-๛0-9]") do
		table.insert(charTbl, c)
	end
	table.sort(charTbl)

	return table.concat(charTbl, "")

end

function export.process(frame)

	local data = require("Module:th-anagram/raw data")
	local hashData = {}
	local hashKey

	-- collect data
	for _, word in ipairs(data) do
		hashKey = hash(word)
		if mw.ustring.len(hashKey) > 1 then
			if not hashData[hashKey] then
				hashData[hashKey] = {}
			end
			if not contains(hashData[hashKey], word) then
				table.insert(hashData[hashKey], word)
			end
		end
	end

	-- remove isolated data
	for key, list in pairs(hashData) do
		if #list < 2 then
			hashData[key] = nil
		end
	end

	return require("Module:debug").dump(hashData)

end

function export.show(frame)

	local args = frame:getParent().args
	local head = ((frame.args[1] == "" or frame.args[1] == nil) and PAGENAME or frame.args[1])
	local hashKey = hash(head)

	local output = {}
	local list = require("Module:th-anagram/processed data")[hashKey]

	if list then
		for _, term in ipairs(list) do
			if term ~= head then
				table.insert(output, links.full_link({lang = lang, term = term, sc = script}))
			end
		end
	end

	return "<ul><li>" .. table.concat(output, ", ") .. "</li></ul>"

end

return export