來源格式與預期記錄
這是原創假設轉換例子。輸入限下列欄位的普通、無循環 JSON 形記錄,統一記錄格式及拒絕代碼由本例訂明。若換來源,先修改格式約定。
輸入用「數字:數字」,兩數須為非負安全整數,分母必須大於 0。以最大公因數約簡,原文字仍保存。分子 0 統一成 0/1,分母 0 則拒絕。此記錄只表示比例,未作數量分配。
| 個案 | 輸入記錄(JSON) | 預期輸出(JSON) |
|---|---|---|
| 約簡並保留原文 | {"ratio":"6:9"} | {"ok":true,"value":{"numerator":2,"denominator":3,"source":"6:9"}} |
| 拒絕零分母 | {"ratio":"3:0"} | {"ok":false,"error":"RATIO_RANGE"} |
| 保留零分子 | {"ratio":"0:5"} | {"ok":true,"value":{"numerator":0,"denominator":1,"source":"0:5"}} |
在本機執行轉換
把完整例子以 JavaScript 模組在 Node.js 執行,內含純轉換函數、三個輸入及寫明的預期輸出,對不上便由斷言停止。拒絕個案回傳 ok=false 及代碼,不回傳半份統一記錄。
import assert from 'node:assert/strict';
function ratioRecord(i){
const fail=error=>({ok:false,error});if(!i||typeof i.ratio!=='string'||!/^\d+:\d+$/.test(i.ratio))return fail('RATIO_TEXT');
const [n,d]=i.ratio.split(':').map(Number);if(!Number.isSafeInteger(n)||!Number.isSafeInteger(d)||d<=0)return fail('RATIO_RANGE');
let a=n,b=d;while(b){const remainder=a%b;a=b;b=remainder;}
return {ok:true,value:{numerator:n/a,denominator:d/a,source:i.ratio}};
}
// Original synthetic cases; expected outputs are literal records.
const cases = [
{
"label": "Reduce ratio without losing source",
"input": {
"ratio": "6:9"
},
"expected": {
"ok": true,
"value": {
"numerator": 2,
"denominator": 3,
"source": "6:9"
}
}
},
{
"label": "Reject zero denominator",
"input": {
"ratio": "3:0"
},
"expected": {
"ok": false,
"error": "RATIO_RANGE"
}
},
{
"label": "Preserve zero numerator",
"input": {
"ratio": "0:5"
},
"expected": {
"ok": true,
"value": {
"numerator": 0,
"denominator": 1,
"source": "0:5"
}
}
}
];
for (const sample of cases) {
const actual = ratioRecord(sample.input);
assert.deepEqual(actual, sample.expected);
console.log(sample.label, JSON.stringify(actual));
}
判清邊界個案
6:9 與 0:5 分別怎樣約簡?
查看參考答案
6、9 最大公因數為 3,得 2/3;0、5 最大公因數為 5,得 0/1。兩者都保存原比例文字。