+ Covers all six requested steps with concrete detail.
- Passing a number to encodeURIComponent causes a type error.
a senior polyglot software engineer with deep expertise in multiple programming languages, their idioms, design patterns, standard libraries, and cros
| Category | Development › Coding |
|---|---|
| Tags | TranslatingReformattingDeveloperCode |
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]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.
ChatGPT is most complete but has compile and behavior issues. Gemini is detailed yet truncated, while [C] is absent.
+ Covers all six requested steps with concrete detail.
- Passing a number to encodeURIComponent causes a type error.
+ Preserves the original shape with a standard decorator.
- It is truncated and partly misstates exception behavior.
| Criterion | ChatGPT | Gemini | Leader |
|---|---|---|---|
| Instruction following | 9 | 6 | ChatGPT +50% |
| Accuracy | 6 | 5 | ChatGPT +20% |
| Specificity | 9 | 8 | ChatGPT +13% |
| Structure | 9 | 8 | ChatGPT +13% |
| Right length | 7 | 5 | ChatGPT +40% |
Scored 1–10 by gpt-5.6-sol with model names hidden (2026-09-24). This is an AI review, not a measurement.
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.
[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)asyncio: 비동기 실행 및 지연aiohttp: HTTP 클라이언트dataclasses: 데이터 클래스functools.wraps: 데코레이터 메타데이터 보존asyncio → JavaScript Promise, async/await, setTimeoutaiohttp → Node.js 20 내장 fetchdataclass → TypeScript interface 또는 classwraps → 직접 대응 불필요fetch 사용. 별도 HTTP 라이브러리가 필요하지 않음상품 ID 목록을 받아 inventory API에서 상품 정보를 비동기로 조회하고, 일시적인 HTTP 클라이언트 오류 발생 시 재시도하는 클라이언트입니다.
Product: 상품 데이터 모델retry: 비동기 함수용 재시도 데코레이터InventoryClient.fetch_product: 단일 상품 조회InventoryClient.fetch_products: 여러 상품 병렬 조회fetch_product 코루틴 생성base_url: stringproduct_id: numberproduct_ids: number[]ProductProduct[]| # | 소스 | 타깃 | 비고 |
|---|---|---|---|
| 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로 정규화 |
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;
}
번역 노트
float와 JavaScript의 number를 매핑했습니다.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');
}
번역 노트
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)));
}
번역 노트
fetch가 전역 제공되므로 세션 객체가 필요하지 않습니다.response.ok를 확인해 HTTP 오류를 명시적으로 처리합니다.unknown으로 받은 뒤 검증하여 타입 안전성을 확보했습니다.Promise.all은 Python의 asyncio.gather와 마찬가지로 하나라도 실패하면 전체가 실패합니다./**
* 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)),
);
}
}
| 항목 | 내용 |
|---|---|
| 구성 요소 | Product, InventoryClient, 재시도 함수, 응답 검증 함수 |
| 라이브러리 교체 | aiohttp → Node.js 내장 fetch |
| 패러다임 변화 | 데코레이터 → 제네릭 고차 함수 |
| 번역 불가능 항목 | Python dataclass의 런타임 생성 동작 |
| 적용한 우회 방식 | parseProduct를 통한 런타임 타입 검증 |
| 스타일 가이드 | TypeScript ESLint/Airbnb 스타일에 준하는 명시적 타입 및 camelCase |
| 타입 안정성 | API 응답을 unknown으로 받은 후 검증 |
| 동작 차이 | HTTP 4xx/5xx를 오류로 처리하도록 개선 |
| 런타임 고려사항 | Node.js 20 이상에서 전역 fetch 필요 |
resp.json() 전에 상태 코드를 검사하지 않지만, 번역본은 비정상 HTTP 상태를 오류로 처리합니다.Promise.all은 하나의 상품 조회라도 최종 실패하면 전체 요청이 실패합니다.AbortSignal을 추가할 수 있습니다.baseUrl 및 productId별도 패키지가 필요하지 않습니다.
npm install -D typescript @types/node
| 12-Month AI and Computer Vision Roadmap for Defense Applications | |
| 2046 Puzzle Game Challenge | |
| 21st.dev component prompt | |
| 3D FACTORY | |
| 3D FPS Game |