mirror of https://github.com/mpv-player/mpv
TOOLS/lua/autoload: further optimize the natural sorting
Commits257dbdf06f
uses a algorithm of splitting strings into a table of number and string values to achieve natural sorting. This approach works well in most cases, but it does not work well in some specific scenarios. Now let's implement natural sorting with a stronger algorithm. Also fixes indentation. Ref:3cf323f3c4
Closes https://github.com/mpv-player/mpv/issues/8969
This commit is contained in:
parent
8439c084e1
commit
444bcd43b7
|
@ -94,35 +94,19 @@ table.filter = function(t, iter)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
-- splitbynum and alnumcomp from alphanum.lua (C) Andre Bogus
|
-- alphanum sorting for humans in Lua
|
||||||
-- Released under the MIT License
|
-- http://notebook.kulchenko.com/algorithms/alphanumeric-natural-sorting-for-humans-in-lua
|
||||||
-- http://www.davekoelle.com/files/alphanum.lua
|
|
||||||
|
|
||||||
-- split a string into a table of number and string values
|
function alphanumsort(o)
|
||||||
function splitbynum(s)
|
local function padnum(d)
|
||||||
local result = {}
|
local dec, n = string.match(d, "(%.?)0*(.+)")
|
||||||
for x, y in (s or ""):gmatch("(%d*)(%D*)") do
|
return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n)
|
||||||
if x ~= "" then table.insert(result, tonumber(x)) end
|
|
||||||
if y ~= "" then table.insert(result, y) end
|
|
||||||
end
|
end
|
||||||
return result
|
table.sort(o, function(a,b)
|
||||||
end
|
return tostring(a):lower():gsub("%.?%d+",padnum)..("%3d"):format(#b)
|
||||||
|
< tostring(b):lower():gsub("%.?%d+",padnum)..("%3d"):format(#a)
|
||||||
function clean_key(k)
|
end)
|
||||||
k = (' '..k..' '):gsub("%s+", " "):sub(2, -2):lower()
|
return o
|
||||||
return splitbynum(k)
|
|
||||||
end
|
|
||||||
|
|
||||||
-- compare two strings
|
|
||||||
function alnumcomp(x, y)
|
|
||||||
local xt, yt = clean_key(x), clean_key(y)
|
|
||||||
for i = 1, math.min(#xt, #yt) do
|
|
||||||
local xe, ye = xt[i], yt[i]
|
|
||||||
if type(xe) == "string" then ye = tostring(ye)
|
|
||||||
elseif type(ye) == "string" then xe = tostring(xe) end
|
|
||||||
if xe ~= ye then return xe < ye end
|
|
||||||
end
|
|
||||||
return #xt < #yt
|
|
||||||
end
|
end
|
||||||
|
|
||||||
local autoloaded = nil
|
local autoloaded = nil
|
||||||
|
@ -181,7 +165,7 @@ function find_and_add_entries()
|
||||||
end
|
end
|
||||||
return EXTENSIONS[string.lower(ext)]
|
return EXTENSIONS[string.lower(ext)]
|
||||||
end)
|
end)
|
||||||
table.sort(files, alnumcomp)
|
alphanumsort(files)
|
||||||
|
|
||||||
if dir == "." then
|
if dir == "." then
|
||||||
dir = ""
|
dir = ""
|
||||||
|
|
Loading…
Reference in New Issue