🇮🇷 Iran Proxy | https://www.wikipedia.org/wiki/Module:Object_weight
Jump to content

Module:Object weight

Permanently protected module
From Wikipedia, the free encyclopedia

-- This module is based off of [[Module:Person weight]]

local p = {}

local function clean_weight(s)

	s = mw.ustring.gsub(s, 'grams', 'g')
	s = mw.ustring.gsub(s, 'gram', 'g')
	s = mw.ustring.gsub(s, 'gs', 'g')
	s = mw.ustring.gsub(s, 'g[%.,]', 'g')

	s = mw.ustring.gsub(s, 'ounces', 'oz')
	s = mw.ustring.gsub(s, 'ounce', 'oz')
	s = mw.ustring.gsub(s, 'oz[%.,]', 'oz')

	return s
end

local function isnumber(s)
	if s then
		s = mw.ustring.gsub(s, '%+%s*%d+%s*/%s*%d+%s*$', '')
		s = mw.ustring.gsub(s, '%s*[–%-]%s*', '')
		return tonumber(s)
	end
	return nil
end

local function get_convert_weight_args(s)
	local prefer_g = (prefer or '') == 'g'
	local force_g = (enforce or '') == 'g'
	local prefer_oz = (prefer or '') == 'oz'
	local force_oz = (enforce or '') == 'oz'
	
	unconverted = clean_weight(s or '') -- basic unit cleaning
	
	s = mw.ustring.gsub(unconverted, '&[Nn][Bb][Ss][Pp];', ' ')
	
	local g = mw.ustring.find(s, 'g')
	
	local oz = mw.ustring.find(s, 'oz')
	
	if g == nil and oz == nil then
		return '', unconverted
	end
	
	if g ~= nil and oz == nil then
		local n = mw.ustring.sub(s, 1, g - 1)
		if isnumber(n) then
			return {n,'g','oz',0,['abbr']='on'}, mw.ustring.sub(s, g+1)
		end
		return '', unconverted
	end
	
	if oz ~= nil and g == nil then
		local n = mw.ustring.sub(s, 1, oz - 1)
		if isnumber(n) then
			return {n,'oz','g',0,['abbr']='on'}, mw.ustring.sub(s, oz+2)
		end
		return '', unconverted
	end
	
	return '', unconverted
end

function convert_weight(frame, args)
	local targs, str = get_convert_weight_args(args[1])

	if type(targs) == 'table' then
		return frame:expandTemplate{ title = 'convert', args = targs} .. str
	else
		return str
	end
end

function p.weight(frame)
	return convert_weight(frame, frame.args[1] and frame.args or frame:getParent().args)
end

return p