|
66 | 66 | ---@param t any[]
|
67 | 67 | ---@param comparator function|nil
|
68 | 68 | function M.merge_sort(t, comparator)
|
69 |
| - if not comparator then |
70 |
| - comparator = function(left, right) |
71 |
| - return left < right |
| 69 | + if type(M.sort_by) == "function" then |
| 70 | + local t_user = {} |
| 71 | + local origin_index = {} |
| 72 | + |
| 73 | + for _, n in ipairs(t) do |
| 74 | + table.insert(t_user, { |
| 75 | + absolute_path = n.absolute_path, |
| 76 | + executable = n.executable, |
| 77 | + extension = n.extension, |
| 78 | + link_to = n.link_to, |
| 79 | + name = n.name, |
| 80 | + type = n.type, |
| 81 | + }) |
| 82 | + table.insert(origin_index, n) |
72 | 83 | end
|
73 |
| - end |
74 | 84 |
|
75 |
| - split_merge(t, 1, #t, comparator) |
| 85 | + M.sort_by(t_user) |
| 86 | + |
| 87 | + -- do merge sort for prevent memory exceed |
| 88 | + local user_index = {} |
| 89 | + for i, v in ipairs(t_user) do |
| 90 | + if type(v.absolute_path) == "string" and user_index[v.absolute_path] == nil then |
| 91 | + user_index[v.absolute_path] = i |
| 92 | + end |
| 93 | + end |
| 94 | + |
| 95 | + -- if missing value found, then using origin_index |
| 96 | + local mini_comparator = function(a, b) |
| 97 | + local a_index = user_index[a.absolute_path] or origin_index[a.absolute_path] |
| 98 | + local b_index = user_index[b.absolute_path] or origin_index[b.absolute_path] |
| 99 | + |
| 100 | + if type(a_index) == "number" and type(b_index) == "number" then |
| 101 | + return a_index <= b_index |
| 102 | + end |
| 103 | + return (a_index or 0) <= (b_index or 0) |
| 104 | + end |
| 105 | + |
| 106 | + split_merge(t, 1, #t, mini_comparator) -- sort by user order |
| 107 | + else |
| 108 | + if not comparator then |
| 109 | + comparator = function(left, right) |
| 110 | + return left < right |
| 111 | + end |
| 112 | + end |
| 113 | + split_merge(t, 1, #t, comparator) |
| 114 | + end |
76 | 115 | end
|
77 | 116 |
|
78 | 117 | local function node_comparator_name_ignorecase_or_not(a, b, ignorecase)
|
|
150 | 189 |
|
151 | 190 | function M.setup(opts)
|
152 | 191 | M.sort_by = opts.sort_by
|
153 |
| - if M.sort_by == "modification_time" then |
| 192 | + if M.sort_by and type(M.sort_by) == "function" then |
| 193 | + M.node_comparator = M.sort_by |
| 194 | + elseif M.sort_by == "modification_time" then |
154 | 195 | M.node_comparator = M.node_comparator_modification_time
|
155 | 196 | elseif M.sort_by == "case_sensitive" then
|
156 | 197 | M.node_comparator = M.node_comparator_name_case_sensisive
|
|
0 commit comments