gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
Refactoriza el siguiente código para hacerlo mas pequeño y más eficiente: [code]
- User
Refactoriza el siguiente código para hacerlo mas pequeño y más eficiente:
lua - Assistant
Refactoriza el siguiente código para hacerlo mas pequeño y más eficiente:
local M = {}
local config = require('CSSColorConverter.config')
local utils = require('CSSColorConverter.utils')
local convert = require('CSSColorConverter.convert_color')
local buffer = require('CSSColorConverter.buffer_ops')
local tops = require('CSSColorConverter.select_text')
M.setup = function(options)
-- Merge the user-provided options with the default options
config.options = vim.tbl_deep_extend("keep", options or {}, config.options)
-- Enable keymap if they are not disableds
if not config.options.disable_keymaps then
local keymaps_opts = {buffer = 0, silent = true}
vim.api.nvim_create_autocmd('FileType', {
desc = 'CSSColorConverter.nvim keymaps',
pattern = 'css',
callback = function()
local map = vim.keymap.set
map('v', '<leader>cn', ":lua require('CSSColorConverter').get_color_name()<CR>", keymaps_opts)
map('v', '<leader>c#', ":lua require('CSSColorConverter').get_color_conversion('hex')<CR>", keymaps_opts)
map('v', '<leader>ch', ":lua require('CSSColorConverter').get_color_conversion('hsl')<CR>", keymaps_opts)
map('v', '<leader>cl', ":lua require('CSSColorConverter').get_color_conversion('lch')<CR>", keymaps_opts)
map('v', '<leader>cr', ":lua require('CSSColorConverter').get_color_conversion('rgb')<CR>", keymaps_opts)
end,
})
end
-- Show virtual text if the option is enabled
if config.options.display_virtual_text then
M.virtual_text()
end
end
-- Get the virtual color text for the current line
local function get_color_virtual()
local namespace = vim.api.nvim_create_namespace("csscolorconverter")
local line, line_content = buffer.get_current_line_content()
local virtual_text = {}
convert.color_value(line_content, virtual_text)
buffer.show_virtual_text(virtual_text, line, namespace)
end
M.virtual_text = function()
-- Create an autocommand to call the get_color_virtual() function
vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter", "CursorMoved"}, {
pattern = "*.css",
callback = function()
get_color_virtual()
end,
})
end
M.get_color_conversion = function(mode, virtual_text)
local _, line_content = buffer.get_current_line_content()
-- Paste the hex value at the cursor selection
local result, initial = convert.color_value(line_content, virtual_text, mode)
local pos_text, select_text = tops.capture_visual_selection()
M.update_color(initial, select_text, result, pos_text)
end
-- Check if colornames.json file exists, and download it if not
local function check_if_colornames_exist()
local install_path, fname = vim.fn.stdpath('data') .. '/CSSColorConverter/', "colornames.json"
-- Check if a directory exists in this path
if vim.fn.isdirectory(install_path) ~= 1 then
vim.fn.mkdir(install_path, 'p')
end
-- Check if the file exists in the install path
if vim.fn.filereadable(install_path .. fname) ~= 1 then
utils.download_file("https://unpkg.com/color-name-list@10.16.0/dist/colornames.json", install_path .. fname, fname)
vim.notify('[CSSColorConverter] The colorname.json file has been downloaded.', vim.log.levels.INFO)
end
end
-- Get the color name for the current selection
M.get_color_name = function()
local _, line_content = buffer.get_current_line_content()
-- Read the JSON file containing the color names
check_if_colornames_exist()
local ok, data = pcall(M.read_json)
if not ok then
return
end
-- Get the nearest color name to the target hex value and paste it at the cursor
local result, initial = convert.color_value(line_content, nil, "hex")
local pos_text, select_text = tops.capture_visual_selection()
local color_names = data or {}
M.update_color(initial, select_text, result, pos_text, color_names)
end
-- to transform a string by making it lowercase and replacing spaces and symbols with hyphens
local transform_text = function(input)
local result = string.lower(input)
result = string.gsub(result, "['’]", "")
return string.gsub(result, "%W", "-")
end
-- to update a color in the text
M.update_color = function(initial, select_text, result, pos_text, useColorName)
for i = 1, #initial do
if select_text and initial[i] == select_text[1] then
-- If using color names, find the nearest color name
if useColorName then
local color_names = convert.nearest_color(result[i], useColorName)
if color_names then
select_text[1] = transform_text(color_names.name)
vim.print(string.format("[CSSColorConverter] %s is equal to: %s", result[i], color_names.name))
end
-- If not using color names, update the selected text with the result
else
select_text[1] = result[i]
vim.print(string.format("[CSSColorConverter] %s is equal to: %s", initial[i], result[i]))
end
tops.change_text(pos_text, select_text)
end
end
end
return M
You can refactor the Lua code to make it shorter and more efficient by reducing redundancy, simplifying control structures, and using local variables effectively. Here is a refactored version:
local M = {}
local config = require('CSSColorConverter.config')
local utils = require('CSSColorConverter.utils')
local convert = require('CSSColorConverter.convert_color')
local buffer = require('CSSColorConverter.buffer_ops')
local tops = require('CSSColorConverter.select_text')
local function extend_options(user_options)
config.options = vim.tbl_deep_extend("keep", user_options or {}, config.options)
end
local function setup_keymaps()
if config.options.disable_keymaps then return end
local buffer_opts = {buffer = 0, silent = true}
local map = vim.keymap.set
map('v', '<leader>cn', ":lua require('CSSColorConverter').get_color_name()<CR>", buffer_opts)
map('v', '<leader>c#', ":lua require('CSSColorConverter').get_color_conversion('hex')<CR>", buffer_opts)
map('v', '<leader>ch', ":lua require('CSSColorConverter').get_color_conversion('hsl')<CR>", buffer_opts)
map('v', '<leader>cl', ":lua require('CSSColorConverter').get_color_conversion('lch')<CR>", buffer_opts)
map('v', '<leader>cr', ":lua require('CSSColorConverter').get_color_conversion('rgb')<CR>", buffer_opts)
end
local function autocommands()
vim.api.nvim_create_autocmd('FileType', {
desc = 'CSSColorConverter.nvim keymaps',
pattern = 'css',
callback = setup_keymaps,
})
if config.options.display_virtual_text then
M.virtual_text()
end
end
M.setup = function(options)
extend_options(options)
autocommands()
end
local function show_color_virtual()
local namespace = vim.api.nvim_create_namespace("csscolorconverter")
local line, line_content = buffer.get_current_line_content()
local virtual_text = {}
convert.color_value(line_content, virtual_text)
buffer.show_virtual_text(virtual_text, line, namespace)
end
M.virtual_text = function()
vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter", "CursorMoved"}, {
pattern = "*.css",
callback = show_color_virtual,
})
end
local function check_colornames()
local path = vim.fn.stdpath('data') .. '/CSSColorConverter/'
local fname = "colornames.json"
if vim.fn.isdirectory(path) ~= 1 then vim.fn.mkdir(path, 'p') end
if vim.fn.filereadable(path .. fname) ~= 1 then
utils.download_file("https://unpkg.com/color-name-list@10.16.0/dist/colornames.json", path .. fname, fname)
vim.notify('[CSSColorConverter] colornames.json downloaded.', vim.log.levels.INFO)
end
end
M.get_color_conversion = function(mode, virtual_text)
local _, line_content = buffer.get_current_line_content()
local result, initial = convert.color_value(line_content, virtual_text, mode)
local pos_text, select_text = tops.capture_visual_selection()
M.update_color(initial, select_text, result, pos_text)
end
M.get_color_name = function()
local _, line_content = buffer.get_current_line_content()
check_colornames()
local ok, data = pcall(M.read_json)
if not ok then return end
local result, initial = convert.color_value(line_content, nil, "hex")
local pos_text, select_text = tops.capture_visual_selection()
local color_names = data or {}
M.update_color(initial, select_text, result, pos_text, color_names)
end
local function transform_text(input)
return (string.gsub(string.lower(input), "[%'’]", "")):gsub("%W", "-")
end
M.update_color = function(initial, select_text, result, pos_text, useColorName)
for i = 1, #initial do
if select_text and initial[i] == select_text[1] then
local new_text = select_text[1]
if useColorName then
local color_info = convert.nearest_color(result[i], useColorName)
if color_info then
new_text = transform_text(color_info.name)
vim.print(string.format("[CSSColorConverter] %s → %s", result[i], color_info.name))
end
else
new_text = result[i]
vim.print(string.format("[CSSColorConverter] %s → %s", initial[i], result[i]))
end
tops.change_text(pos_text, {new_text})
end
end
end
return M
autocommands function.setup_keymaps, to avoid unnecessary nesting.transform_text to make it more concise.These changes help in making the code more maintainable and readable, while also slightly improving runtime efficiency by reducing unnecessary computations and simplifying control flow.
Not yet included in a published release.