Moduł:odmiana

Z Wikisłownika – wolnego, wielojęzycznego słownika
Skocz do: nawigacja, szukaj
Moduł wykorzystywany przez szablon {{odmiana}}.
local key = {}

local Declension = {
	patt_ref    = '\127UNIQ[^\127]+QINU\127',
	patt_short  = '<span class="short%-container".*</span>',
	default_sep = '/',
	misc = {}
}

function Declension:new( data, misc, aliases, init )
	local myStringGSub, myTextGSplit, myTextTrim = mw.ustring.gsub, mw.text.gsplit, mw.text.trim
	
	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
			if self.patt_ref then
				form = ( myStringGSub( form, self.patt_ref, '' ) )
			end
			
			if self.patt_short then
				form = ( myStringGSub( form, self.patt_short, '' ) )
			end

			if separators then
				for _, sep in pairs( separators ) do
					form = ( myStringGSub( form, sep, self.default_sep or '/' ) )
				end
			end

			k = aliases and aliases[ k ] or k
			temp[ k ] = {}
			
			for w in myTextGSplit( form, '%s?' .. self.default_sep .. '%s?' ) do
				temp[ k ][ #temp[ k ] + 1 ] = ( w ~= '' ) and myTextTrim( 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, ... )
	local myUStringSub, myUStringLen = mw.ustring.sub, mw.ustring.len

	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 myUStringSub( case, -myUStringLen( suffix ) ) == suffix then
				return true
			end
		end
	end

	return false
end

function Declension:startsWith( form, ... )
	local myUStringSub, myUStringLen = mw.ustring.sub, mw.ustring.len

	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 myUStringSub( case, 1, myUStringLen( 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