How I use ChatGPT for refactoring code in my project

While ChatGPT3.5 (current version) is not smart enough to refactor large chunks of code, it can still be a useful tool in refactoring small chunks of code.
Usage could be various, however I’m mentioning a few of them which I’ve personally used
- Optimising function block
- Writing test cases using jest
- Changing code to generate different outputs based on previous output results.

Prompt : Can you help me with code optimisation, you need to use switch case whenever possible

At this step. I copy my code from vscode and past it in the chat window.
Prompt 2: optimise the below code
export const getEnvVariableOrThrow: GetEnvVariableFn = (key) => {
const value = getEnvVariable(key);
if (!value) {
throw new Error(`Environment variable ${key} is not defined`);
}
return value;
}
Here the optimised code it generated.
export const getEnvVariableOrThrow: GetEnvVariableFn = (key) => {
const value = getEnvVariable(key) ?? (() => { throw new Error(`Environment variable ${key} is not defined`); })();
return value;
}
It also responded to what changes have been made and what optimization was performed.
In this version, if
getEnvVariable(key)
returnsnull
orundefined
, it will throw an error using the nullish coalescing operator. This makes the code a bit more concise, but it might not be as readable for everyone. So, it's essential to consider readability and maintainability when optimizing code. In this case, your original version might be preferable due to its clarity.
Pretty amazing! In the next steps, I plan to create a Python bot that’ll automatically refactor my code and generate a pull request. I’ll update you with an article for the same.
If you like my content, consider following to get more funny and interesting articles 🥰.