Actions

Module

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

-- Module:TitleIndex
-- Extract and format a year range from began_publication / ended_publication

local p = {}

local function firstYear(str)
	if not str or str == "" then
		return nil
	end
	for y in tostring(str):gmatch("(%d%d%d%d)") do
		return y
	end
	return nil
end

local function lastYear(str)
	if not str or str == "" then
		return nil
	end
	local last
	for y in tostring(str):gmatch("(%d%d%d%d)") do
		last = y
	end
	return last
end

-- Generic arg merger: direct #invoke args override parent template args
local function getArgs(frame)
	local parent = frame:getParent()
	local out = {}

	-- 1) Arguments passed directly to #invoke
	for k, v in pairs(frame.args or {}) do
		if v ~= "" then
			out[k] = v
		end
	end

	-- 2) Fall back to parent template arguments
	if parent and parent.args then
		for k, v in pairs(parent.args) do
			if out[k] == nil or out[k] == "" then
				out[k] = v
			end
		end
	end

	return out
end

function p.range(frame)
	local args = getArgs(frame)

	-- Support both the template’s param names and generic ones
	local began = args.began or args.began_publication or args[1] or ""
	local ended = args.ended or args.ended_publication or args[2] or ""
	local seriesType = (args.type or args[3] or ""):lower()

	local byear = firstYear(began)
	local eyear = lastYear(ended)

	if not byear and not eyear then
		return ""
	end

	-- Only begin year → ongoing, show trailing dash
	if byear and not eyear then
		return byear .. " – "
	end

	-- Only end year (weird, but handle it)
	if not byear and eyear then
		return eyear
	end

	-- Same year
	if byear == eyear then
		return byear
	end

	-- Normal range
	return byear .. " – " .. eyear
end

return p