Documentation icon دستاویز [تخلیق]
-- This module finds the highest existing archive number for a set of talk
-- archive pages.

local p = {}

local function pageExists(page)
	local success, exists = pcall(function()
		return mw.title.new(page).exists
	end)
	return success and exists
end

local function midPoint(lower, upper)
	return math.floor(lower + (upper - lower) / 2)
end

local function findHighestArchive(prefix, i, lower, upper)
	if i < 1 then
		return nil
	elseif pageExists(prefix .. tostring(i)) then
		lower = i
		if upper and i + 1 == upper then
			return i
		elseif upper then
			i = midPoint(lower, upper)
		else
			i = i * 2
		end
		return findHighestArchive(prefix, i, lower, upper)
	else
		upper = i
		lower = lower or 0
		i = midPoint(lower, upper)
		return findHighestArchive(prefix, i, lower, upper)
	end
end

function p._main(prefix)
	if type(prefix) ~= 'string' or not prefix:find('%S') then
		error('no prefix supplied to [[Module:Highest archive number]]', 2)
	end
	return findHighestArchive(prefix, 10)
end

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame, {
		trim = false,
		removeBlanks = false,
		wrappers = 'Template:Highest archive number'
	})
	local prefix = args[1]
	return p._main(prefix)
end

return p