Module:SortedKeys

From Ways of Darkness
Jump to navigation Jump to search

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

function getKeysSortedByValue(tbl, sortFunction)
  local keys = {}
  for key in pairs(tbl) do
    table.insert(keys, key)
  end

  table.sort(keys, function(a, b)
    return sortFunction(tbl[a], tbl[b])
  end)

  return keys
end

function table.sort_by_value(tbl)
  local sortedKeys = getKeysSortedByValue(tbl, function(a, b) return a > b end)
  local tmp_tbl = {}
  for _, key in ipairs(sortedKeys) do
    tmp_tbl[key] = tbl[key]
  end
  return tmp_tbl
end
function table.sort_by_value_reverse(tbl)
  local sortedKeys = getKeysSortedByValue(tbl, function(a, b) return a < b end)
  local tmp_tbl = {}
  for _, key in ipairs(sortedKeys) do
    tmp_tbl[key] = tbl[key]
  end
  return tmp_tbl
end
function table.sort_by_inside_value(tbl,val)
  local sortedKeys = getKeysSortedByValue(tbl, function(a, b) return a[val] > b[val] end)
  local tmp_tbl = {}
  for _, key in ipairs(sortedKeys) do
    tmp_tbl[key] = tbl[key]
  end
  return tmp_tbl
end