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 - function p.sortedPairsByValue(t, keySort) checkType('sortedPairs', 1, t, 'table') checkType('sortedPairs', 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: sortedPairsToList(t: table, keySort?: function|boolean, customFn?: function|boolean) -- -- Iterates through a table, sorted using either a default comparison -- function or a custom keySort function on the value, then -- squashes it into a table using the custom function -- which default to return all keys - function p.sortedPairsToList(t, keySort, customFn) checkType('sortedPairs', 1, t, 'table') checkType('sortedPairs', 2, keySort, { 'function', 'boolean', 'nil' }) checkType('sortedPairs', 2, customFn, { '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

-- 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 }, }	for k, v in p.sortedPairsCustom(t, function(a, b)		return a.order < b.order	end) do		mw.log(k) mw.logObject(v) end end

return p