Jump to content

Module:Japanese calendar

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 15:06, 21 August 2013 (finish the era class definition). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

local eras = mw.loadData( 'Module:Japanese calendar/data' )

--------------------------------------------------------------------
-- Helper functions
--------------------------------------------------------------------

local function yearToEraIndex( year )
    local currentYear = tonumber( mw.language.getContentLanguage():formatDate( 'Y' ) )
    year = tonumber( year )
    if type( year ) ~= 'number' or year > currentYear then return end
    for i, t in ipairs( eras ) do
        if year >= t.year then
            return i
        end
    end
end

local function textToEraIndex( s )
    for i, t in ipairs( eras ) do
        if s == t.article or s == t.kanji then
            return i
        end
    end
end

--------------------------------------------------------------------
-- Era class definition
--------------------------------------------------------------------

local era = {}
era.__index = era

function era:new( init )
    init = type( init ) == 'table' and init or {}
    local obj = {}
    
    obj.gregorianYear = init.year
    obj.article = init.article
    obj.kanji = init.kanji
    obj.label = init.label
    
    if obj.gregorianYear then
        -- We have the Gregorian year, so we can calculate all the data.
        local eraIndex = yearToEraIndex( obj.gregorianYear )
        if eraIndex then
            local eraData = eras[ eraIndex ]
            obj.startYear = eraData.year
            obj.eraYear = obj.gregorianYear - obj.startYear + 1
            obj.eraYearKanji = tostring( obj.eraYear )
            if obj.eraYearKanji == '1' then
                obj.eraYearKanji = '元'
            end
            obj.article = eraData.article
            obj.kanji = eraData.kanji
            obj.label = eraData.label
        end
    elseif obj.article or obj.kanji then
        -- No year was specified, so we will take what data we can from the article name or from the kanji.
        local eraIndex = textToEraIndex( obj.article ) or textToEraIndex( obj.kanji )
        if eraIndex then
            local eraData = eras[ eraIndex ]
            obj.startYear = eraData.year
            obj.kanji = eraData.kanji
            obj.label = eraData.label
        end
    end
    -- Create a link to the era article if possible.
    if obj.article then
        if obj.label then
            obj.link = mw.ustring.format( '[[%s|%s]]', obj.article, obj.label )
        else
            obj.link = mw.ustring.format( '[[%s]]', obj.article )
        end
    end
    
    return setmetatable( obj, {
        __index = self
    })
end    

return era