Jump to content

Module:Shorten

From UoB Wiki

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

require('strict')

local getArgs = require('Module:Arguments').getArgs
local p = {}

local function makeInvokeFunc(funcName, wrappers)
	return function (frame)
		local args = getArgs(frame, {
			wrappers = wrappers
		})
		return p[funcName](args)
	end
end

local function makeInsensitive(pattern)
    return (pattern:gsub("%a", function(c)
        return string.format("[%s%s]", string.lower(c), string.upper(c))
    end))
end

p.shorten = makeInvokeFunc('_shorten', { 'Template:Shorten' })
function p._shorten(args)
	local replace_map = {
		['bachelor of science'] = "BSc",
		['bachelor of arts'] = "BA",
		['doctor of philosophy'] = "PhD",
		['master of science'] = "MSc",
		['department of '] = "",
		['college of '] = ""
	}
	
	local input_text
	local link
	if args[2] == nil then
		input_text = args[1]
		link = nil
	else
		input_text = args[2]
		link = args[1]
	end
	
	local function formatOutput(text)
		if link ~= nil then
			return '[[' .. link .. '|' .. text .. ']]'
		end
		return '[[' .. input_text .. '|' .. text .. ']]'
	end
	
	for program, abbr in pairs(replace_map) do
		local res, count = input_text:gsub(makeInsensitive(program), abbr)
		if count ~= 0 then
			return formatOutput(res)
		end
	end
	return formatOutput(input_text)
end

return p