Module:Sandbox/Johnuniq/unit

-- Test the helper function in Module:Convert to get unit information.

-- Usage: {{#invoke:sandbox/Johnuniq/unit|main}}

-- See Module talk:Sandbox/Johnuniq/unit.

local function collection()

-- Return a table to hold items.

return {

n = 0,

add = function (self, item)

self.n = self.n + 1

self[self.n] = item

end,

join = function (self, sep)

return table.concat(self, sep)

end,

}

end

local tests = {

-- unitcode value flags (L=link, N=name, U=us, S=sort)

'kg',

'kg 12.3 L',

'm',

'm -1 S',

'm 12 L S',

'km L',

'ft 99 L',

'km3 L',

'km3 12.3 N',

'km3 12.3 L N',

'km3 12.3 L N U',

'km3 12.3 L N U S',

'foo',

'foo L S',

}

local function make_args(text)

local flags = { L='link', N='name', U='us', S='sort' }

local unitcode, options

local show = collection()

show:add('unit(')

for item in text:gmatch('%S+') do

if unitcode then

local k, v

k = flags[item]

if k then

if item == 'S' then

v = 'on'

else

v = 'true'

end

else

k = 'value'

v = tonumber(item)

end

if options then

show:add(', ')

else

options = {}

show:add(', {')

end

options[k] = v

show:add(k .. '=' .. v)

else

unitcode = item

show:add("'" .. item .. "'")

end

end

if options then

show:add('}')

end

show:add(')')

return unitcode, options, show:join()

end

local function main(frame)

local get_unit = require('Module:Convert/sandbox')._unit

local results = collection()

for _, item in ipairs(tests) do

local unitcode, options, show = make_args(item)

local unit = get_unit(unitcode, options)

results:add('')

results:add('> ' .. show)

results:add(string.format('%40s %9s %s',

unit.text,

unit.unknown and '(unknown)' or '',

unit.sortspan or ''

))

end

return '

\n' .. mw.text.nowiki(results:join('\n')) .. '\n
\n'

end

return { main = main }