☰ Categories

Code Translator — Idiomatic, Version-Aware & Production-Ready

a senior polyglot software engineer with deep expertise in multiple programming languages, their idioms, design patterns, standard libraries, and cros

CategoryDevelopment › Coding
TagsTranslatingReformattingDeveloperCode
Prompt
You are a senior polyglot software engineer with deep expertise in multiple 
programming languages, their idioms, design patterns, standard libraries, 
and cross-language translation best practices.

I will provide you with a code snippet to translate. Perform the translation
using the following structured flow:

---

📋 STEP 1 — Translation Brief
Before analyzing or translating, confirm the translation scope:

- 📌 Source Language  : [Language + Version e.g., Python 3.11]
- 🎯 Target Language  : [Language + Version e.g., JavaScript ES2023]
- 📦 Source Libraries : List all imported libraries/frameworks detected
- 🔄 Target Equivalents: Immediate library/framework mappings identified
- 🧩 Code Type        : e.g., script / class / module / API / utility
- 🎯 Translation Goal : Direct port / Idiomatic rewrite / Framework-specific
- ⚠️  Version Warnings : Any target version limitations to be aware of upfront

---

🔍 STEP 2 — Source Code Analysis
Deeply analyze the source code before translating:

- 🎯 Code Purpose      : What the code does overall
- ⚙️  Key Components   : Functions, classes, modules identified
- 🌿 Logic Flow        : Core logic paths and control flow
- 📥 Inputs/Outputs    : Data types, structures, return values
- 🔌 External Deps     : Libraries, APIs, DB, file I/O detected
- 🧩 Paradigms Used    : OOP, functional, async, decorators, etc.
- 💡 Source Idioms     : Language-specific patterns that need special 
                         attention during translation

---

⚠️ STEP 3 — Translation Challenges Map
Before translating, identify and map every challenge:

LIBRARY & FRAMEWORK EQUIVALENTS:
| # | Source Library/Function | Target Equivalent | Notes |
|---|------------------------|-------------------|-------|

PARADIGM SHIFTS:
| # | Source Pattern | Target Pattern | Complexity | Notes |
|---|---------------|----------------|------------|-------|

Complexity: 
- 🟢 [Simple]  — Direct equivalent exists
- 🟡 [Moderate]— Requires restructuring
- 🔴 [Complex] — Significant rewrite needed

UNTRANSLATABLE FLAGS:
| # | Source Feature | Issue | Best Alternative in Target |
|---|---------------|-------|---------------------------|

Flag anything that:
- Has no direct equivalent in target language
- Behaves differently at runtime (e.g., null handling, 
  type coercion, memory management)
- Requires target-language-specific workarounds
- May impact performance differently in target language

---

🔄 STEP 4 — Side-by-Side Translation
For every key logic block identified in Step 2, show:

[BLOCK NAME — e.g., Data Processing Function]

SOURCE ([Language]):
```[source language]
[original code block]
```

TRANSLATED ([Language]):
```[target language]
[translated code block]
```

🔍 Translation Notes:
- What changed and why
- Any idiom or pattern substitution made
- Any behavior difference to be aware of

Cover all major logic blocks. Skip only trivial 
single-line translations.

---

🔧 STEP 5 — Full Translated Code
Provide the complete, fully translated production-ready code:

Code Quality Requirements:
- Written in the TARGET language's idioms and best practices
  · NOT a line-by-line literal translation
  · Use native patterns (e.g., JS array methods, not manual loops)
- Follow target language style guide strictly:
  · Python → PEP8
  · JavaScript/TypeScript → ESLint Airbnb style
  · Java → Google Java Style Guide
  · Other → mention which style guide applied
- Full error handling using target language conventions
- Type hints/annotations where supported by target language
- Complete docstrings/JSDoc/comments in target language style
- All external dependencies replaced with proper target equivalents
- No placeholders or omissions — fully complete code only

---

📊 STEP 6 — Translation Summary Card

Translation Overview:
Source Language  : [Language + Version]
Target Language  : [Language + Version]
Translation Type : [Direct Port / Idiomatic Rewrite]

| Area                    | Details                                    |
|-------------------------|--------------------------------------------|
| Components Translated   | ...                                        |
| Libraries Swapped       | ...                                        |
| Paradigm Shifts Made    | ...                                        |
| Untranslatable Items    | ...                                        |
| Workarounds Applied     | ...                                        |
| Style Guide Applied     | ...                                        |
| Type Safety             | ...                                        |
| Known Behavior Diffs    | ...                                        |
| Runtime Considerations  | ...                                        |

Compatibility Warnings:
- List any behaviors that differ between source and target runtime
- Flag any features that require minimum target version
- Note any performance implications of the translation

Recommended Next Steps:
- Suggested tests to validate translation correctness
- Any manual review areas flagged
- Dependencies to install in target environment:
  e.g., npm install [package] / pip install [package]

---

Here is my code to translate:

Source Language : [SPECIFY SOURCE LANGUAGE + VERSION]
Target Language : [SPECIFY TARGET LANGUAGE + VERSION]

[PASTE YOUR CODE HERE]

What this prompt does

Useful for porting or idiomatically rewriting code between languages. It asks the model to map libraries, paradigm shifts, and untranslatable features before producing the translation.

Model comparison

ChatGPT is most complete but has compile and behavior issues. Gemini is detailed yet truncated, while [C] is absent.

ChatGPTTop overall
40/ 50

+ Covers all six requested steps with concrete detail.

- Passing a number to encodeURIComponent causes a type error.

Gemini
32/ 50

+ Preserves the original shape with a standard decorator.

- It is truncated and partly misstates exception behavior.

CriterionChatGPTGeminiLeader
Instruction following96ChatGPT +50%
Accuracy65ChatGPT +20%
Specificity98ChatGPT +13%
Structure98ChatGPT +13%
Right length75ChatGPT +40%

Scored 1–10 by gpt-5.6-sol with model names hidden (2026-09-24). This is an AI review, not a measurement.

Read full answers

We gave three models the same input and copied their answers unedited. Each ran in its CLI (an agent harness), and answers in the ChatGPT or Claude apps or on the web may differ. Outputs are in Korean.

Input used
[Pasted material]
Source Language : Python 3.11
Target Language : TypeScript (Node.js 20, ES2023)

import asyncio
import aiohttp
from dataclasses import dataclass
from functools import wraps

@dataclass
class Product:
    id: int
    name: str
    price: float
    stock: int

def retry(max_attempts=3, delay=1):
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            last_exception = None
            for attempt in range(max_attempts):
                try:
                    return await func(*args, **kwargs)
                except aiohttp.ClientError as e:
                    last_exception = e
                    await asyncio.sleep(delay * (attempt + 1))
            raise last_exception
        return wrapper
    return decorator

class InventoryClient:
    def __init__(self, base_url: str):
        self.base_url = base_url

    @retry(max_attempts=3)
    async def fetch_product(self, product_id: int) -> Product:
        async with aiohttp.ClientSession() as session:
            async with session.get(f"{self.base_url}/products/{product_id}") as resp:
                data = await resp.json()
                return Product(**data)

    async def fetch_products(self, product_ids: list[int]) -> list[Product]:
        tasks = [self.fetch_product(pid) for pid in product_ids]
        return await asyncio.gather(*tasks)
gpt-5.6-luna (codex CLI · 에이전트 하네스) · Run on 2026-09-24

📋 STEP 1 — 번역 개요

  • 소스 언어: Python 3.11
  • 타깃 언어: TypeScript, Node.js 20, ES2023
  • 소스 라이브러리:
    • asyncio: 비동기 실행 및 지연
    • aiohttp: HTTP 클라이언트
    • dataclasses: 데이터 클래스
    • functools.wraps: 데코레이터 메타데이터 보존
  • 타깃 대응:
    • asyncio → JavaScript Promise, async/await, setTimeout
    • aiohttp → Node.js 20 내장 fetch
    • dataclass → TypeScript interface 또는 class
    • wraps → 직접 대응 불필요
  • 코드 유형: 비동기 HTTP 클라이언트 모듈
  • 번역 목표: 타입 안전성을 갖춘 idiomatic rewrite
  • 버전 경고: Node.js 20의 내장 fetch 사용. 별도 HTTP 라이브러리가 필요하지 않음

🔍 STEP 2 — 소스 코드 분석

전체 목적

상품 ID 목록을 받아 inventory API에서 상품 정보를 비동기로 조회하고, 일시적인 HTTP 클라이언트 오류 발생 시 재시도하는 클라이언트입니다.

주요 구성 요소

  • Product: 상품 데이터 모델
  • retry: 비동기 함수용 재시도 데코레이터
  • InventoryClient.fetch_product: 단일 상품 조회
  • InventoryClient.fetch_products: 여러 상품 병렬 조회

로직 흐름

  1. 상품 ID별로 fetch_product 코루틴 생성
  2. 각 HTTP 요청을 병렬 실행
  3. 실패 시 최대 3회 재시도
  4. 재시도 간격은 1초, 2초, 3초
  5. 모든 요청 완료 후 상품 배열 반환

입출력

  • 입력:
    • base_url: string
    • product_id: number
    • product_ids: number[]
  • 출력:
    • Product
    • Product[]
  • 외부 의존성:
    • HTTP API
    • 네트워크 연결

사용된 패러다임

  • 객체 지향 프로그래밍
  • 비동기 프로그래밍
  • 데코레이터 기반 재시도
  • 병렬 작업 처리

⚠️ STEP 3 — 번역 과제 맵

라이브러리 및 프레임워크 대응

# 소스 타깃 비고
1 asyncio.sleep setTimeout 기반 delay 함수 밀리초 단위로 변환
2 aiohttp.ClientSession Node.js 내장 fetch 별도 패키지 불필요
3 asyncio.gather Promise.all 병렬 작업 처리
4 @dataclass interface Product 런타임 생성자 대신 타입과 검증 함수 사용
5 @retry 고차 함수 withRetry TypeScript에서는 명시적 함수 래퍼가 더 단순하고 안전함

패러다임 변화

# 소스 패턴 타깃 패턴 복잡도 비고
1 Python 데코레이터 제네릭 재시도 함수 🟡 Moderate 메서드 데코레이터보다 타입 추론이 명확함
2 dataclass 생성 JSON 검증 후 객체 반환 🟡 Moderate TypeScript 타입은 런타임 검증을 수행하지 않음
3 aiohttp.ClientError Error 및 HttpError 🟡 Moderate HTTP 상태 코드 처리를 명시적으로 추가
4 초 단위 sleep 밀리초 단위 timer 🟢 Simple delay * 1000 필요

번역 불가능하거나 주의할 항목

# 소스 기능 문제 타깃 대안
1 Python dataclass TypeScript interface는 런타임 검증을 하지 않음 parseProduct 함수로 검증
2 aiohttp 예외 체계 fetch는 HTTP 4xx/5xx에서 자동 throw하지 않음 response.ok 확인 및 HttpError 생성
3 asyncio.gather 하나의 Promise가 실패하면 전체 실패 Promise.all로 동일 동작
4 raise last_exception TypeScript에서는 반드시 Error 객체를 throw하는 것이 안전 마지막 예외를 Error로 정규화

🔄 STEP 4 — 주요 로직별 번역

상품 모델

SOURCE (Python)

@dataclass
class Product:
    id: int
    name: str
    price: float
    stock: int

TRANSLATED (TypeScript)

export interface Product {
  id: number;
  name: string;
  price: number;
  stock: number;
}

번역 노트

  • Python의 float와 JavaScript의 number를 매핑했습니다.
  • TypeScript interface는 컴파일 시 타입만 제공하므로 런타임 JSON 검증은 별도 함수로 처리합니다.

재시도 로직

SOURCE (Python)

def retry(max_attempts=3, delay=1):
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            last_exception = None
            for attempt in range(max_attempts):
                try:
                    return await func(*args, **kwargs)
                except aiohttp.ClientError as e:
                    last_exception = e
                    await asyncio.sleep(delay * (attempt + 1))
            raise last_exception
        return wrapper
    return decorator

TRANSLATED (TypeScript)

async function withRetry<T>(
  operation: () => Promise<T>,
  maxAttempts = 3,
  delaySeconds = 1,
): Promise<T> {
  let lastError: Error | undefined;

  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
    try {
      return await operation();
    } catch (error) {
      lastError = toError(error);

      if (attempt === maxAttempts - 1) {
        break;
      }

      await delay(delaySeconds * (attempt + 1) * 1000);
    }
  }

  throw lastError ?? new Error('Operation failed without an error');
}

번역 노트

  • TypeScript에서는 데코레이터보다 명시적인 고차 함수가 구현과 타입 추론 측면에서 적합합니다.
  • 원본과 동일하게 재시도 간격은 1초, 2초, 3초입니다.
  • 마지막 시도 후에는 추가 대기를 하지 않도록 했습니다.

단일 상품 조회 및 병렬 조회

SOURCE (Python)

@retry(max_attempts=3)
async def fetch_product(self, product_id: int) -> Product:
    async with aiohttp.ClientSession() as session:
        async with session.get(f"{self.base_url}/products/{product_id}") as resp:
            data = await resp.json()
            return Product(**data)

async def fetch_products(self, product_ids: list[int]) -> list[Product]:
    tasks = [self.fetch_product(pid) for pid in product_ids]
    return await asyncio.gather(*tasks)

TRANSLATED (TypeScript)

async fetchProduct(productId: number): Promise<Product> {
  return withRetry(async () => {
    const response = await fetch(
      `${this.baseUrl}/products/${encodeURIComponent(productId)}`,
    );

    if (!response.ok) {
      throw new HttpError(
        `Inventory API returned HTTP ${response.status}`,
        response.status,
      );
    }

    const data: unknown = await response.json();
    return parseProduct(data);
  });
}

async fetchProducts(productIds: number[]): Promise<Product[]> {
  return Promise.all(productIds.map((productId) => this.fetchProduct(productId)));
}

번역 노트

  • Node.js 20에서는 fetch가 전역 제공되므로 세션 객체가 필요하지 않습니다.
  • response.ok를 확인해 HTTP 오류를 명시적으로 처리합니다.
  • 응답 JSON을 unknown으로 받은 뒤 검증하여 타입 안전성을 확보했습니다.
  • Promise.all은 Python의 asyncio.gather와 마찬가지로 하나라도 실패하면 전체가 실패합니다.

🔧 STEP 5 — 전체 번역 코드

/**
 * Product returned by the inventory API.
 */
export interface Product {
  id: number;
  name: string;
  price: number;
  stock: number;
}

/**
 * Error raised when the inventory API returns a non-success status.
 */
export class HttpError extends Error {
  public readonly status: number;

  public constructor(message: string, status: number) {
    super(message);
    this.name = 'HttpError';
    this.status = status;
  }
}

/**
 * Converts unknown thrown values into Error instances.
 */
function toError(error: unknown): Error {
  return error instanceof Error ? error : new Error(String(error));
}

/**
 * Waits for the specified number of milliseconds.
 */
function delay(milliseconds: number): Promise<void> {
  return new Promise((resolve) => {
    setTimeout(resolve, milliseconds);
  });
}

/**
 * Executes an asynchronous operation with linear backoff retries.
 *
 * Delays between attempts are:
 * delaySeconds, delaySeconds * 2, delaySeconds * 3, ...
 */
async function withRetry<T>(
  operation: () => Promise<T>,
  maxAttempts = 3,
  delaySeconds = 1,
): Promise<T> {
  if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
    throw new RangeError('maxAttempts must be a positive integer');
  }

  if (!Number.isFinite(delaySeconds) || delaySeconds < 0) {
    throw new RangeError('delaySeconds must be a non-negative number');
  }

  let lastError: Error | undefined;

  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
    try {
      return await operation();
    } catch (error) {
      lastError = toError(error);

      if (attempt === maxAttempts - 1) {
        break;
      }

      await delay(delaySeconds * (attempt + 1) * 1000);
    }
  }

  throw lastError ?? new Error('Operation failed without an error');
}

/**
 * Validates and converts an unknown API response into a Product.
 */
function parseProduct(value: unknown): Product {
  if (typeof value !== 'object' || value === null) {
    throw new TypeError('Product response must be an object');
  }

  const product = value as Record<string, unknown>;

  if (
    typeof product.id !== 'number' ||
    !Number.isInteger(product.id) ||
    typeof product.name !== 'string' ||
    typeof product.price !== 'number' ||
    !Number.isFinite(product.price) ||
    typeof product.stock !== 'number' ||
    !Number.isInteger(product.stock)
  ) {
    throw new TypeError('Product response has an invalid shape');
  }

  return {
    id: product.id,
    name: product.name,
    price: product.price,
    stock: product.stock,
  };
}

/**
 * Client for retrieving products from an inventory API.
 */
export class InventoryClient {
  private readonly baseUrl: string;

  public constructor(baseUrl: string) {
    const normalizedBaseUrl = baseUrl.trim().replace(/\/+$/, '');

    if (!normalizedBaseUrl) {
      throw new Error('baseUrl must not be empty');
    }

    try {
      new URL(normalizedBaseUrl);
    } catch {
      throw new Error(`Invalid baseUrl: ${baseUrl}`);
    }

    this.baseUrl = normalizedBaseUrl;
  }

  /**
   * Fetches one product by ID.
   *
   * @param productId Numeric product identifier.
   * @returns The requested product.
   */
  public async fetchProduct(productId: number): Promise<Product> {
    if (!Number.isInteger(productId)) {
      throw new TypeError('productId must be an integer');
    }

    return withRetry(async () => {
      const response = await fetch(
        `${this.baseUrl}/products/${encodeURIComponent(productId)}`,
      );

      if (!response.ok) {
        throw new HttpError(
          `Inventory API returned HTTP ${response.status}`,
          response.status,
        );
      }

      const data: unknown = await response.json();
      return parseProduct(data);
    });
  }

  /**
   * Fetches multiple products concurrently.
   *
   * @param productIds Numeric product identifiers.
   * @returns Products in the same order as the supplied IDs.
   */
  public async fetchProducts(productIds: number[]): Promise<Product[]> {
    return Promise.all(
      productIds.map((productId) => this.fetchProduct(productId)),
    );
  }
}

📊 STEP 6 — 번역 요약 카드

항목 내용
구성 요소 Product, InventoryClient, 재시도 함수, 응답 검증 함수
라이브러리 교체 aiohttp → Node.js 내장 fetch
패러다임 변화 데코레이터 → 제네릭 고차 함수
번역 불가능 항목 Python dataclass의 런타임 생성 동작
적용한 우회 방식 parseProduct를 통한 런타임 타입 검증
스타일 가이드 TypeScript ESLint/Airbnb 스타일에 준하는 명시적 타입 및 camelCase
타입 안정성 API 응답을 unknown으로 받은 후 검증
동작 차이 HTTP 4xx/5xx를 오류로 처리하도록 개선
런타임 고려사항 Node.js 20 이상에서 전역 fetch 필요

호환성 경고

  • Node.js 20 이상을 사용해야 합니다.
  • 원본 Python 코드는 resp.json() 전에 상태 코드를 검사하지 않지만, 번역본은 비정상 HTTP 상태를 오류로 처리합니다.
  • 번역본은 HTTP 오류와 네트워크 오류 모두 재시도합니다.
  • Promise.all은 하나의 상품 조회라도 최종 실패하면 전체 요청이 실패합니다.
  • 현재 구현은 요청 취소를 지원하지 않으므로 필요하면 AbortSignal을 추가할 수 있습니다.

권장 테스트

  • 정상적인 상품 응답
  • 잘못된 JSON 구조
  • HTTP 404 및 500 응답
  • 네트워크 오류 후 재시도 성공
  • 최대 재시도 횟수 초과
  • 빈 상품 ID 배열
  • 잘못된 baseUrl 및 productId

설치할 의존성

별도 패키지가 필요하지 않습니다.

npm install -D typescript @types/node

More in this category

12-Month AI and Computer Vision Roadmap for Defense Applications
2046 Puzzle Game Challenge
21st.dev component prompt
3D FACTORY
3D FPS Game