Refactor a Function for Clarity and Performance
Transform messy, complex, or slow functions into clean, readable, and efficient code while preserving exact behavior.
The Prompt
Refactor the following function. Goals: 1. Improve readability — clearer naming, shorter lines, reduced nesting 2. Improve performance — eliminate redundant work, better data structures 3. Preserve exact behavior — do not change what the function does 4. Add JSDoc/docstring explaining the function, parameters, and return value After the refactored code, briefly explain the key changes you made and why. Original function: ``` [PASTE YOUR FUNCTION HERE] ```
Example Output
Reduced the function from 47 lines to 18 by extracting a helper, replacing three nested for-loops with a single `.reduce()`, and using early returns to eliminate deep nesting. Behavior is identical — verified against the original logic.
FAQ
Which AI model is best for Refactor a Function for Clarity and Performance?
GPT-4o or Claude Sonnet 4. For large complex functions (500+ lines), prefer Claude for its 200K context window.
How do I use the Refactor a Function for Clarity and Performance prompt?
Copy the prompt, replace the [BRACKETED] placeholders with your specific information, and paste into your preferred AI assistant (ChatGPT, Claude, Gemini, etc.). Reduced the function from 47 lines to 18 by extracting a helper, replacing three nested for-loops with a single `.reduce()`, and using early returns to eliminate deep nesting. Behavior is identical — verified against the original logic.
Model Recommendation
GPT-4o or Claude Sonnet 4. For large complex functions (500+ lines), prefer Claude for its 200K context window.