Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ndruger/dafdf392de8c5374bb2e8fcb6b25cc14 to your computer and use it in GitHub Desktop.

Select an option

Save ndruger/dafdf392de8c5374bb2e8fcb6b25cc14 to your computer and use it in GitHub Desktop.

GPT-4's Answer

It is possible to refactor only the internals of functions within a large class using GPT-4. Here's an approach to achieve that:

npx ts-node refactorAndCombine.ts /path/to/your/typescript/file.ts

refactor_function.py

import openai
import sys

# Replace with your OpenAI API key
api_key = 'your-openai-api-key'

openai.api_key = api_key

def refactor_function(function_body):
    prompt = f"""I have a TypeScript function that needs to be refactored. Please refactor the internal code of the function without changing the function signature or input/output types. Make the code more efficient, readable, and maintainable, while preserving the original functionality. Here is the original function body:

{function_body}

Please provide the refactored code for this function body."""

    response = openai.Completion.create(
        engine='text-davinci-002',  # Replace with the desired GPT-4 engine name
        prompt=prompt,
        max_tokens=150,
        n=1,
        stop=None,
        temperature=0.5,
    )

    refactored_code = response.choices[0].text.strip()
    return refactored_code

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python refactor_function.py <function_body>")
        sys.exit(1)

    function_body = sys.argv[1]
    refactored_code = refactor_function(function_body)

    print("Original function body:")
    print(function_body)
    print("\nRefactored function body:")
    print(refactored_code)

refactorAndCombine.ts

import * as ts from 'typescript';
import { exec } from 'child_process';

function extractFunctions(sourceFile: ts.SourceFile): ts.FunctionDeclaration[] {
  const functions: ts.FunctionDeclaration[] = [];

  function visit(node: ts.Node) {
    if (ts.isFunctionDeclaration(node)) {
      functions.push(node);
    }

    ts.forEachChild(node, visit);
  }

  visit(sourceFile);

  return functions;
}

function execAsync(command: string): Promise<string> {
  return new Promise((resolve, reject) => {
    exec(command, (error, stdout, stderr) => {
      if (error) {
        reject(error);
      } else {
        resolve(stdout);
      }
    });
  });
}

async function refactorFunction(functionBody: string): Promise<string> {
  const stdout = await execAsync(`python refactor_function.py "${functionBody}"`);
  const refactoredCode = stdout.split('\nRefactored function body:\n')[1];
  return refactoredCode.trim();
}

async function main() {
  const filePath = process.argv[2];
  if (!filePath) {
    console.error('Please provide a TypeScript file path.');
    process.exit(1);
  }

  const sourceCode = ts.sys.readFile(filePath);
  if (!sourceCode) {
    console.error('Failed to read the TypeScript file.');
    process.exit(1);
  }

  const sourceFile = ts.createSourceFile(
    filePath,
    sourceCode,
    ts.ScriptTarget.ESNext,
    true
  );

  const functions = extractFunctions(sourceFile);

  let refactoredSourceCode = sourceCode;

  for (const func of functions) {
    const funcCode = sourceCode.substring(func.pos, func.end);
    const refactoredFuncCode = await refactorFunction(funcCode);
    refactoredSourceCode = refactoredSourceCode.replace(funcCode, refactoredFuncCode);
  }

  ts.sys.writeFile(filePath, refactoredSourceCode);

  console.log(`Refactored TypeScript code has been saved to: ${filePath}`);
}

main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment