Jump to content

Module:columns/auto/sandbox

From Wiktionary, the free dictionary


local export = {}
local m_links = require("Module:links")

function export.extract_lengths(text)
	local lengths = {}
	local items = mw.text.decode(m_links.remove_links(text):gsub("<.->", "")):gmatch("\n%* ([^\n]+)")
	for i in items do
		table.insert(lengths, #i)
	end
	return lengths
end

function export.decide_number_of_columns(lang, number_of_items, lengths)
	local max_length = math.max(unpack(lengths))
	local avg_length = 0
	for _, i in ipairs(lengths) do avg_length = avg_length + i/#lengths end
	local l = (avg_length + max_length)/2
	
	if l <= 10 then
		return 5
	elseif l <= 20 then
		return 4
	elseif l <= 30 then
		return 3
	elseif l <= 40 then
		return 2
	else
		return 1
	end
end

function export.display_from(column_args, list_args)
	local m_table = require("Module:table")
	column_args = m_table.shallowcopy(column_args)
	local lang = require("Module:languages").getByCode(mw.text.trim(list_args[1]), 1)
	column_args["columns"] = 1
	local output = require("Module:columns").display_from(column_args, list_args)
	local lengths = export.extract_lengths(output)
	local n_columns = export.decide_number_of_columns(lang, m_table.length(list_args), export.extract_lengths(output))
	output = output:gsub('data%-column%-count="1"', 'data-column-count="' .. n_columns .. '"')
	return output
end

function export.display(frame)
	return export.display_from(frame.args, frame:getParent().args)
end

return export