Module:Core

Revision as of 09:19, 15 August 2016 by がか (talk | contribs)

Documentation for this module may be created at Module:Core/doc

local Utils = {}

function Utils.method(frame)
	local m = require("Module:" .. frame.args[1])
	local f = frame.args[2]
	local args = {}
	for k, v in ipairs(frame.args) do
		if type(k) == "number" and k >= 3 and type(v) == "string" then
			table.insert(args, v)
		end
	end
	return m[f](m, unpack(args))
end

function Utils.find(tbl, v_, k_)
	for _, v in pairs(tbl) do
		if k_ and v[k_] == v_ or not k_ and v == v_ then
			return true
		end
	end
	return false
end

function Utils.map(tbl, fn)
	local result = {}
	for _, v in pairs(tbl) do
		table.insert(result, fn(v))
	end
	return result
end
 
function Utils.filter(tbl, pred)
	local result = {}
	for _, v in pairs(tbl) do
		if pred(v) then
			table.insert(result, v)
		end
	end
	return result
end

function Utils.ifirst(tbl)
    for k, v in ipairs(tbl) do
        return k, v
    end
end

function Utils.first(tbl)
    for k, v in pairs(tbl) do
        return k, v
    end
end

local getArgs = require("Module:GetArgs")

function Utils.getContext(frame)
    local parentFrame = frame:getParent()
    return { pagename = parentFrame:getTitle(), args = getArgs{ frame = parentFrame } }
end

function Utils.test_context(frame)
    local context = Utils.getContext(frame)
    return "arg = " .. (context.args.arg or "?") .. " @ " .. (context.pagename or "?")
end

return Utils