بازنویسی کد قدیمی به نسخه تمیز و قابل نگهداری
یک تابع یا فایل درهم را بده و نسخهای بگیر که همان رفتار را دارد ولی خواناتر و قابل تست است، با فهرست تغییرها و تستهایی که ثابت میکنند رفتار عوض نشده.
- انتشار
- ۲۶ آبان ۱۴۰۵
- اجرا
- ۳ بار
نمونه خروجی
۱. کد بازنویسیشده
```javascript
const VAT_RATE = 0.1;
function applyDiscount(price, code) {
if (code === "YALDA") return price * 0.85;
if (code === "VIP") return price * 0.8;
return price;
}
function calcTotal(items, code) {
let subtotal = 0;
for (const item of items) {
subtotal += applyDiscount(item.price, code) * item.qty;
}
return Math.round(subtotal * (1 + VAT_RATE));
}
```
۲. تغییرات
- عدد جادویی 0.1 به ثابت VAT_RATE تبدیل شد.
- منطق تخفیف به تابع جدا رفت.
- متغیرهای a و t به item و subtotal تغییر نام دادند.
۳. تستها
```javascript
test("no code", () => expect(calcTotal([{ price: 1000, qty: 2 }])).toBe(2200));
test("YALDA", () => expect(calcTotal([{ price: 1000, qty: 1 }], "YALDA")).toBe(935));
```
۴. باگهای مشکوک
- کد «yalda» با حروف کوچک تخفیف نمیگیرد؛ رفتار حفظ شد.
چه چیزی لازم داری
کد قدیمی و توضیح رفتاری که باید حفظ شود
متن پرامپت
پرامپت انگلیسیکدClaudeRefactor this code without changing its behavior.
Language: [language and version]
Behavior that must stay identical: [describe, including odd edge cases that callers rely on]
Code:
```
[paste]
```
Rules:
- Same inputs produce the same outputs and side effects. If you believe something is a bug, keep the behavior and flag it separately in a "suspected bugs" list; do not silently fix it.
- Split long functions, name things by what they mean, remove dead code and duplication, add types where the language supports them.
- No new dependencies.
Output:
1. The refactored code.
2. A list of changes, one line each, in Persian.
3. Unit tests (using the standard test framework for this language) that would pass on both the old and the new code, covering the edge cases above.
4. The suspected bugs list, if any.بعد از اجرا یا کپی، بگو برایت جواب داد یا نه.
چطور اجرا کنم
- دکمهٔ اجرا را بزن تا پرامپت در jostoju باز شود، یا متن را کپی کن و در ابزار دلخواهت بگذار.
- کد قدیمی و توضیح رفتاری که باید حفظ شود را به آن بده.
- جایخالیهای داخل [ ] را با اطلاعات خودت پر کن.
- اگر نتیجه دقیقاً آن چیزی نبود که میخواستی، یک جمله توضیح اضافه کن و دوباره اجرا کن.
پرامپت انگلیسی؛ مدلها پرامپت انگلیسی را هم با ورودی فارسی خوب میفهمند. کلمهای ناآشنا بود؟ واژهنامه.