Module:Graph:Utils

local p = {}

function p.titleToJson(title) -- Load mediawiki page and decodes it as json local t = mw.title.new(title) if not t.exists then return nil else return mw.text.jsonDecode(t:getContent, mw.text.JSON_TRY_FIXING) end end

function p.recodeListToMap(frame) -- a function to re-code a json table in format [{},{},{}] to a map {}, -- with each source object containing the same set of values, and the response -- mapping the "from" value to "to" value -- parameters: tbl, from, to	local args = frame.args local tbl = p.titleToJson(args[1]) local from = args[2] local to = args[3] local result = p.recodeListToMapFunc(tbl, from, to, args) return mw.text.jsonEncode(result) end function p.recodeListToMapFunc(tbl, from, to, values) -- a function to re-code a json table in format [{},{},{}] to a map {}, -- with each source object containing the same set of values, and the response -- mapping the "from" values to "to" values -- parameters: tbl, from, to	local dict = {} for k, v in pairs(tbl) do		if v[from] ~= nil and v[to] ~= nil then dict[v[from]] = v[to] end end local result = {} for key, val in pairs(values) do		if type(key) == "string" then local k = dict[key] if k ~= nil then result[k] = val end end end return result end

function p.parseCsv(frame) local args = frame.args local content = mw.title.new(args[1]):getContent local numberIdx = tonumber(args[2]) local result = p.parseCsvFunc(content, numberIdx) return mw.text.jsonEncode(result) end

function p.parseCsvFunc(content, numberIdx) -- Simple, no escaping, csv parser. Assumes first row contains columns local result = {} local isFirstRow = true

for v in string.gmatch(content, '([^\n]*)') do		local val = mw.text.trim(v) if val ~= '' then local parts = mw.text.split( val, ',', true ) if isFirstRow then isFirstRow = false else table.insert(result, {					id=mw.text.trim(parts[1]),					v=tonumber(mw.text.trim(parts[numberIdx]))				}) end end end return result end

return p