Module:Ja

local p = {}

-- Smallify input text containing parenthesized text local function smallify(parenText) if not parenText then return nil end local match = mw.ustring.match local first = match(parenText, '([^(]+)%(.*%)') or match(parenText, '([^（]+)（.*）' )   local rest = match(parenText, '[^(]+%s?(%([^)]+%))') or match(parenText, '[^（]+%s?(（[^）]+）)' )    if not rest then return parenText    else return first .. ' ' .. rest .. ' ' end end

-- Template:ja-r function p.rubify(frame) local gmatch = mw.ustring.gmatch local args = frame:getParent.args local ja, kana = args[1], args[2] local errorMsg = ' Error in Module:Ja:rubify: Kanji and kana do not match. '   -- ancillary functions local splitBy = function (str, pattern) if not pattern then pattern = '%s' end local result = {} for word in gmatch(str, '([^' .. pattern .. ']+)') do table.insert( result, word ) end return result end local splitIntoChars = function (str) local result = {} for char in gmatch(str, '.') do table.insert(result, char) end return result end

-- split individual kanji local splitJa = splitIntoChars(ja)

-- split kana by space local splitKana = splitBy(kana)

-- check that previous splits are equal; -- if not, return errorMsg if #splitJa ~= #splitKana then return errorMsg end

-- else, iterate through both splits and rubify N kanji and kana local result = {} local i = 1 while i <= #splitJa do       if splitJa[i] == splitKana[i] then table.insert(result, splitJa[i]) else table.insert(result, ' ' .. splitJa[i] .. '（' .. splitKana[i] .. '） ') end i = i + 1 end return table.concat(result, '') end

function p.ja(frame) local args = frame:getParent.args local compressSparseArray = require('Module:TableTools').compressSparseArray local errorMsg = ' Error in Module:Ja:ja: Expected argument values, but received none. '   local separator = function(sep, bool) return bool and sep or '' end local init = args[1] local ja, rom = args[2] and smallify(args[2]), args[3] and  .. smallify(args[3]) ..    if ja ==  then ja = nil elseif rom ==  then rom = nil end local jaRom = (ja or rom) and ( ja or '' ) .. separator(', ', ja and rom) .. ( rom or '') local lit = args['lit'] and 'literally "' .. args['lit'] .. '"' local dh = args['dh'] and 'Dark Horse: ' .. args['dh'] local outputTxt = { jaRom, lit, dh } outputTxt = init .. ' (' .. table.concat( compressSparseArray(outputTxt), '; ' ) .. ')'

if outputTxt == ' ' then return errorMsg else return outputTxt end end

return p

--