大量重複 if-else 判斷利率、期限、幣種,代碼超過 500 行,維護極其困難。NaN 因未解析數值直接運算。
change 處理器,根據 e.target.id 分發。calculate(input) 無副作用,易測試。const CONFIG = {
currencies: [
{id:1, name:'人民幣', symbol:'元', rates:{1:0.55, 2:1.1, 3:1.1, 4:1.35, 5:1.55, 6:1.75, 7:2.25, 63:2.75, 8:2.75}},
{id:2, name:'美元', symbol:'美元', rates:{9:0.05, 10:0.2, 11:0.3, 12:0.5, 13:0.8, 14:0.8}},
// ... 其他幣種
],
terms: {
'd1':1, 'd7':7, 'm1':30, 'm3':90, 'm6':180, 'y1':360, 'y2':720, 'y3':1080, 'y5':1800
}
};
function calculate(principal, rate, days) {
if (!principal || !rate || !days) return {interest:0, total:0, tax:0};
const interest = principal * (days/360) * (rate/100);
return {
interest: interest.toFixed(2),
total: (principal + interest).toFixed(2),
tax: '0.00' // 利息稅暫為0
};
}
$(document).on('change', '#sel1, #sel2, #input1, #nl4, #nl3', function(e) {
const $target = $(e.target);
// 1. 幣種變更 → 更新利率下拉、符號
if ($target.is('#sel1')) updateCurrency($target.val());
// 2. 期限變更 → 重新計算
if ($target.is('#sel2')) recalc();
// 3. 本金/利率/天數變更 → 重新計算
if ($target.is('#input1, #nl3, #nl4')) recalc();
});
function recalc() {
const currency = CONFIG.currencies.find(c => c.id == $('#sel1').val());
const termId = $('#sel2').val();
const rate = currency.rates[termId];
const days = CONFIG.terms[$('#sel2').find('option:selected').attr('name')];
const principal = parseFloat($('#input1').val()) || 0;
const result = calculate(principal, rate, days);
$('#lj').val(result.interest);
$('#lj1').val(result.total);
$('#lj2').val(result.tax);
$('#dw, #dw1, #dw2').val(currency.symbol);
}
| 指標 | 重構前 | 重構後 |
|---|---|---|
| 代碼行數 | 500+ | ~120 |
| 新增幣種 | 改 10+ 處 | 加 1 配置項 |
| 新增期限 | 加 if-else | 加 1 配置項 |
| 測試難度 | 極高 | 純函數易測試 |
| NaN 問題 | 頻發 | parseFloat||0 兜底 |
將**業務規則外部化為配置**,用**事件委託+純函數計算**替換硬編碼 if-else,是前端複雜表單重構的黃金模式。代碼從「寫給機器看」變為「寫給人看、配置給機器用」。