Jump to content

Module:Highest archive number: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
split the midpoint-finding code out into its own function
remove the automatic prefix-finding code - this might introduce subtle bugs
Line 35: Line 35:


function p._main(prefix)
function p._main(prefix)
if not prefix then
if type(prefix) ~= 'string' or not string:find('%S') then
error('no prefix supplied to [[Module:Highest archive number]]', 2)
-- Try to detect whether we are on an archive page or not and create
-- the prefix accordingly.
local title = mw.title.getCurrentTitle()
prefix = title.prefixedText:match('^(.*/Archive )[0-9]+$')
prefix = prefix or title.prefixedText .. '/Archive '
end
end
return findHighestArchive(prefix, 10)
return findHighestArchive(prefix, 10)

Revision as of 03:34, 7 October 2014

-- This module finds the highest existing archive number for a set of talk
-- archive pages.

local p = {}

local function pageExists(page)
	local success, title = pcall(mw.title.new, page)
	return success and title and title.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 string: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