وحدة:Wikidata2/functions2

من أرابيكا، الموسوعة الحرة
اذهب إلى التنقل اذهب إلى البحث
local help_functions = {}

help_functions.sortingproperties = {"P585", "P571", "P580", "P569", "P582", "P570"}
help_functions.sorting_methods = {
	["chronological"] = "chronological",
	["تصاعدي"] = "chronological",
	["asc"] = "chronological",
	["inverted"] = "inverted",
	["تنازلي"] = "inverted",
	["desc"] = "inverted"
}

function help_functions.comparedates(a, b) -- returns true if a is earlier than B or if a has a date but not b
	if a and b then
		return a > b
	elseif a then
		return true
	end
end

function help_functions.getqualifierbysortingproperty(claim, sortingproperty)
	for k, v in pairs(sortingproperty) do
		if claim.qualifiers and claim.qualifiers[v] and claim.qualifiers[v][1].snaktype == "value" then
			local vali = claim.qualifiers[v][1].datavalue.value.time or claim.qualifiers[v][1].datavalue.value.amount
			if vali:sub(1, 1) == "+" then
				vali = vali:sub(2)
			end
			--mw.log(vali)
			return vali
		end
	end
	return nil
end

function help_functions.get_sorting_properties(options)
	if type(options.sortingproperty) == "table" then
		return options.sortingproperty
	elseif type(options.sortingproperty) == "string" and options.sortingproperty ~= "" then
		return mw.text.split(options.sortingproperty, ",")
	else
		return help_functions.sortingproperties
	end
end

function help_functions.sortbyqualifiernumber(claims, sorting_properties, options)
	if not sorting_properties or #sorting_properties == 0 then
		sorting_properties = help_functions.get_sorting_properties(options)
	end

	local sort_by = help_functions.sorting_methods[options.sortbynumber] or options.sortbynumber

	table.sort(
		claims,
		function(a, b)
			local timeA = help_functions.getqualifierbysortingproperty(a, sorting_properties)
			local timeB = help_functions.getqualifierbysortingproperty(b, sorting_properties)
			if sort_by == "inverted" then
				return help_functions.comparedates(timeB, timeA)
			else
				return help_functions.comparedates(timeA, timeB)
			end
		end
	)
	return claims
end

return help_functions