Module:Sandbox/MonkeysHK

local table = require('Module:Table') local checkType = require('Module:LibraryUtil').checkTypeLight local p = {}

local defaultKeySort = function(a, b)	return a < b end

- -- function: sortedPairsByValue(t: table, keySort?: function|boolean) -- -- Iterates through a table, sorted using either a default comparison -- function or a custom keySort function on the value -- Returns a generator - function p.sortedPairsByValue(t, keySort) checkType('sortedPairsByValue', 1, t, 'table') checkType('sortedPairsByValue', 2, keySort, { 'function', 'boolean', 'nil' }) local function toArray(t) local ret = {} for k, v in pairs(t) do			table.push(ret, { key = k, value = v }) end return ret end local list = toArray(table.deepCopy(t, true)) if keySort ~= false then keySort = type(keySort) == 'function' and keySort or defaultKeySort table.sort(list, function(a, b)			a, b = a.value, b.value			return keySort(a, b)		end) end local i = 0 return function i = i + 1 local data = list[i] if data ~= nil then return data.key, data.value else return nil, nil end end end

- -- function: toCustomArrayNamed(t: table, customFn?: table|generator) -- -- Iterates through a named table or using a generator, map each values -- returned by a custom function into a table -- There is no indexed table counterpart because that would be the same as p.map - function p.toCustomArrayNamed(t, customFn) checkType('toCustomArrayNamed', 1, t, { 'function', 'table' }) checkType('toCustomArrayNamed', 2, customFn, { 'function', 'nil' }) local ret = {} customFn = type(customFn) == 'function' and customFn or function(v, k) return k end if type(t) == 'function' then -- t as generator for k, v in t do			table.push(ret, customFn(v, k, t)) end else -- t as table for k, v in pairs(t) do			table.push(ret, customFn(v, k, t)) end end return ret end

-- testing code function p.test local t = { ['3rd element'] = { name = 'Foo', order = 3 }, ['1st element'] = { name = 'Bar', order = 1 }, ['0th element'] = { name = 'Baz', order = 0 }, ['2nd element'] = { name = 'Foobar', order = 2 }, }	local function MyGenerator return p.sortedPairsByValue(t, function(a, b)			return a.order < b.order		end) end mw.log('\n\n\nFirst test\n\n') for k, v in MyGenerator do		mw.log(k) mw.logObject(v) end mw.log('\n\n\nSecond test\n\n') mw.logObject(p.toCustomArrayNamed(MyGenerator)) mw.logObject(p.toCustomArrayNamed(MyGenerator, function(v, k)		return v.name end)) -- unordered mw.logObject(p.toCustomArrayNamed(t, function(v, k)		return v.name end)) end

return p