refactor(utils): make prepend_line_numbers() more efficient and idiomatic

Between Utils.prepend_line_number() and its only caller, there is a lot
of conversions from list to string to list and back to string. Simplify
all of this by making it accept and return a list of strings, which
avoids unnecessary splitting and joining.

The implementation was updated to use vim.iter():map() and
string.format() for better performance and to align with the idiomatic
functional style used elsewhere in the project.

The name of the function has also been tweaked and is now
"prepend_line_numbers()" to better reflect that it operates on a list of
strings.

The caller has been updated to match the new function signature.
This commit is contained in:
Dmitry Torokhov
2025-08-06 15:31:26 -07:00
committed by yetone
parent 76fe3f615a
commit 638d237b75
2 changed files with 10 additions and 10 deletions

View File

@@ -166,8 +166,10 @@ function Suggestion:suggest()
local bufnr = api.nvim_get_current_buf() local bufnr = api.nvim_get_current_buf()
local filetype = api.nvim_get_option_value("filetype", { buf = bufnr }) local filetype = api.nvim_get_option_value("filetype", { buf = bufnr })
local code_content = local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false)
Utils.prepend_line_number(table.concat(api.nvim_buf_get_lines(bufnr, 0, -1, false), "\n") .. "\n\n") table.insert(lines, "")
table.insert(lines, "")
local code_content = table.concat(Utils.prepend_line_numbers(lines), "\n")
local full_response = "" local full_response = ""

View File

@@ -718,15 +718,13 @@ function M.get_doc()
return doc return doc
end end
function M.prepend_line_number(content, start_line) ---Prepends line numbers to each line in a list of strings.
---@param lines string[] The lines of content to prepend line numbers to.
---@param start_line? integer The starting line number. Defaults to 1.
---@return string[] A new list of strings with line numbers prepended.
function M.prepend_line_numbers(lines, start_line)
start_line = start_line or 1 start_line = start_line or 1
local lines = vim.split(content, "\n") return vim.iter(lines):map(function(line, i) return string.format("L%d: %s", i + start_line, line) end):totable()
local result = {}
for i, line in ipairs(lines) do
i = i + start_line - 1
table.insert(result, "L" .. i .. ": " .. line)
end
return table.concat(result, "\n")
end end
---Iterates through a list of strings and removes prefixes in form of "L<number>: " from them ---Iterates through a list of strings and removes prefixes in form of "L<number>: " from them