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:
@@ -166,8 +166,10 @@ function Suggestion:suggest()
|
||||
|
||||
local bufnr = api.nvim_get_current_buf()
|
||||
local filetype = api.nvim_get_option_value("filetype", { buf = bufnr })
|
||||
local code_content =
|
||||
Utils.prepend_line_number(table.concat(api.nvim_buf_get_lines(bufnr, 0, -1, false), "\n") .. "\n\n")
|
||||
local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false)
|
||||
table.insert(lines, "")
|
||||
table.insert(lines, "")
|
||||
local code_content = table.concat(Utils.prepend_line_numbers(lines), "\n")
|
||||
|
||||
local full_response = ""
|
||||
|
||||
|
||||
@@ -718,15 +718,13 @@ function M.get_doc()
|
||||
return doc
|
||||
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
|
||||
local lines = vim.split(content, "\n")
|
||||
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")
|
||||
return vim.iter(lines):map(function(line, i) return string.format("L%d: %s", i + start_line, line) end):totable()
|
||||
end
|
||||
|
||||
---Iterates through a list of strings and removes prefixes in form of "L<number>: " from them
|
||||
|
||||
Reference in New Issue
Block a user