Module:Wikidades/Units

Lua
CodeDiscussionLinksLink count SubpagesDocumentationTestsResultsSandboxLive code All modules

Local configuration helper module to get units of a Wikidata numeric value.

Table wikidata_units

The format for each unit is:

Qid = {
label = 'xxx',
plural = 'xxx',
ucode = 'xxx',
},

Inclusion in this table is optional:

  • Qid is the unit identifier in Wikidata, used as a reference.
  • label is the unit tag in Wikidata. It is automatically retrieved from the Wikidata query or may be included here if you want a different value in the infobox, or in high use cases to avoid sudden and massive changes due to a Wikidata modification, whether vandalic or not.
  • plural is the plural of the unit tag, to be used when the quantity is different than 1. It is automatically generated from rules (see ca:Module:ca-flexió) and will only need to be included in non-regular cases.
  • ucode is the unit code or abbreviation, to be used if you use the formatting = unitcode parameter. You only need to add it when the value is different from that obtained from unit symbol (P5061). If none is found they will remove the tag.
Table convert_default

Default unit conversions used with the convert = default option. The format is:

Qid_from = 'Qid_to', - comment

where Qid_from is the identifier of the unit to be converted and Qid_to is the unit used in the conversion. It is advisable to explain in a comment which units are for better reading. See the documentation for the formatting parameters for numeric data type.

Code

-- syntax:
--	Qxxx = { -- label from Wikidata, as a reference
--		label = "label fixed",
--		plural = "plural fixed",
--		ucode = "unit code to add or to fix",
--		},

local wikidata_units = {
	Q4917 = { -- United States dollar
		ucode = "$", -- shortcut, often used
		},
	Q11229 = { -- percent
		ucode = "%", -- shortcut, often used
		},
	Q11573 = { -- metre
		ucode = "m", -- shortcut, often used
		},
	Q712226 = { -- square kilometre
		ucode = "km²", -- shortcut, often used
		},
	}

local function getUnit(amount, label, unitID, code, symbol)
	if label == nil then return unitID end
	local id_data = wikidata_units[unitID] or {}
	local unit_text = ''
	if code then
		unit_text = id_data.ucode or symbol or id_data.label
	elseif amount == "1" then
		unit_text = id_data.label
	else
		unit_text = id_data.plural or id_data.label
	end
	return unit_text or label or unitID
end

local convert_default = {
	Q218593 = "Q174789", -- in > mm
	Q3710 = "Q174728", -- ft > cm
	Q482798 = "Q11573", -- yd > m
	Q253276 = "Q828224", -- mi > km
	Q232291 = "Q712226", -- mi² > km²
	Q128822 = "Q180154", -- knot > km/h
}

return {
	getUnit = getUnit,
	convert_default = convert_default
}