1
0

Can now sort string indexes that are actually numbers

This commit is contained in:
Jon Michael Aanes 2017-10-22 13:06:21 +02:00
parent a9d4d35fc1
commit 94dd6acb0c
2 changed files with 11 additions and 7 deletions

View File

@ -104,9 +104,8 @@ local VALUE_TYPE_SORT_ORDER = {
--------------------------------------------------------------------------------
-- Key-value-pair Util
local function padnum(d)
local dec, n = string.match(d, "(%.?)0*(.+)")
return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n)
local function padnum(minus, dec, zeroes, n)
return dec == '.' and ("%.12f"):format(dec..zeroes..n) or ("%s%03d%s"):format(minus == '' and ':' or minus, #n, n)
end
local function alphanum_compare_strings (a, b)
@ -115,8 +114,13 @@ local function alphanum_compare_strings (a, b)
assert(type(a) == 'string')
assert(type(b) == 'string')
local a_padded = a:gsub("%.?%d+", padnum)..("\0%3d"):format(#b)
local b_padded = b:gsub("%.?%d+", padnum)..("\0%3d"):format(#a)
local a_padded = a:gsub("(%-?)(%.?)(0*)(%d+)", padnum)..("\0%3d"):format(#b)
local b_padded = b:gsub("(%-?)(%.?)(0*)(%d+)", padnum)..("\0%3d"):format(#a)
-- Correction for sorting of negative numbers:
if a_padded:sub(1,1) == '-' and b_padded:sub(1,1) == '-' then
a_padded, b_padded = b_padded, a_padded
end
--
local A_padded, B_padded = a_padded:upper(), b_padded:upper()
if A_padded == B_padded then return a_padded < b_padded end
return A_padded < B_padded

View File

@ -87,8 +87,8 @@ format_test {
format_test {
name = 'Proper sorting of number strings keys',
input = { ['-100'] = 'a', ['-1'] = 'b', ['0'] = 'c', ['1'] = 'd', ['100'] = 'e' },
expect = '{\n [\'-100\'] = \'b\', [\'-1\'] = \'c\',\n [\'0\'] = \'d\', [\'1\'] = \'e\',\n [\'100\'] = \'f\'\n}',
input = { ['-10'] = 'a', ['-0.5'] = 'b', ['0'] = 'c', ['1'] = 'd', ['10.1'] = 'e' },
expect = '{\n [\'-10\'] = \'a\', [\'-0.5\'] = \'b\',\n [\'0\'] = \'c\', [\'1\'] = \'d\',\n [\'10.1\'] = \'e\'\n}',
}