Jump to content

Module:Highest archive number: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
fix a bug in the recursion algorithm, try to guess the prefix if we are not provided with one, and make this usable from wikitext
split the midpoint-finding code out into its own function
Line 7: Line 7:
local success, title = pcall(mw.title.new, page)
local success, title = pcall(mw.title.new, page)
return success and title and title.exists
return success and title and title.exists
end

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


Line 17: Line 21:
return i
return i
elseif upper then
elseif upper then
i = math.floor(lower + (upper - lower) / 2)
i = midPoint(lower, upper)
else
else
i = i * 2
i = i * 2
Line 25: Line 29:
upper = i
upper = i
lower = lower or 0
lower = lower or 0
i = math.floor(lower + (upper - lower) / 2)
i = midPoint(lower, upper)
return findHighestArchive(prefix, i, lower, upper)
return findHighestArchive(prefix, i, lower, upper)
end
end

Revision as of 06:11, 6 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 not prefix then
		-- 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
	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