[go: up one dir, main page]

Moduł wykorzystywany przez szablon {{odmiana}}.


local key = {}

local Declension = {
	patt_short  = '<span class="short%-container">%[%[.-%]%]</span>',
	patt_pot    = '<span class="potential%-form"[^>]*>(.-)</span>',
	default_sep = '/',
	misc = {}
}

function Declension:new( data, misc, aliases, init )
	for _, v in ipairs( ( type( misc ) == 'table' ) and misc or { misc } ) do
		self.misc[ v ] = data[ v ]
		data[ v ] = nil
	end

	local separators = self.separators
	separators = separators
		and ( ( type( separators ) == 'table' )
			and separators
			or { separators } )
		or nil
	separators = ( #separators ~= 0 ) and separators or nil

	local temp = {}

	for k, form in pairs( data or {} ) do
		if form ~= '' then
			form = mw.text.killMarkers( form )
			
			if self.patt_short then
				form = ( mw.ustring.gsub( form, self.patt_short, '' ) )
			end
			
			if self.patt_pot then
				form = mw.ustring.gsub( form, self.patt_pot, '%1' )
			end

			if separators then
				for _, sep in pairs( separators ) do
					form = ( mw.ustring.gsub( form, sep, self.default_sep ) )
				end
			end

			k = aliases and aliases[ k ] or k
			temp[ k ] = {}
			
			for w in mw.text.gsplit( form, self.default_sep, true ) do
				temp[ k ][ #temp[ k ] + 1 ] = ( w ~= '' ) and mw.text.trim( w ) or nil
			end

			temp[ k ] = ( #temp[ k ] ~= 0 ) and temp[ k ] or nil
		end
	end

	local o = init and init( temp ) or {}

	o[ key ] = temp
	setmetatable( o, self )
	self.__index = self

	return o
end

function Declension:missingForm( ... )
	local missing = false
	for _, form in ipairs( arg ) do
		if not self[ key ][ form ] then
			missing = true
			break
		end
	end
	return missing
end

function Declension:endsWith( form, ... )
	if not self[ key ][ form ] or #arg == 0 then return false end

	for _, case in pairs( self[ key ][ form ] ) do
		for _, suffix in ipairs( arg ) do
			if mw.ustring.sub( case, -mw.ustring.len( suffix ) ) == suffix then
				return true
			end
		end
	end

	return false
end

function Declension:startsWith( form, ... )
	if not self[ key ][ form ] or #arg == 0 then return false end

	for _, case in pairs( self[ key ][ form ] ) do
		for _, prefix in ipairs( arg ) do
			if mw.ustring.sub( case, 1, mw.ustring.len( prefix ) ) == prefix then
				return true
			end
		end
	end

	return false
end

function Declension:equals( a, b )
	if not self[ key ][ a ] then return false end

	for _, va in pairs( self[ key ][ b ] or { b } ) do
		for _, vb in pairs( self[ key ][ a ] ) do
			if va == vb then return true end
		end
	end

	return false
end

function Declension:getForm( form )
	return self[ key ][ form ]
end

local p = {
	Declension = Declension
}

return p