來源格式與預期記錄
這是原創假設轉換例子。輸入限下列欄位的普通、無循環 JSON 形記錄,統一記錄格式及拒絕代碼由本例訂明。若換來源,先修改格式約定。
畫面及矩形的闊、高須為正安全整數,x、y 為非負安全整數。矩形須全在畫面內,可貼邊。x、闊除以畫面闊,y、高除以畫面高,並保存 sourceSize,unit 列 fraction。
| 個案 | 輸入記錄(JSON) | 預期輸出(JSON) |
|---|---|---|
| 換算已提供矩形 | {"surface":{"width":200,"height":100},"rect":{"x":20,"y":10,"width":100,"height":40}} | {"ok":true,"value":{"left":0.1,"top":0.1,"width":0.5,"height":0.4,"unit":"fraction","sourceSize":{"width":200,"height":100}}} |
| 拒絕超出邊界 | {"surface":{"width":200,"height":100},"rect":{"x":190,"y":0,"width":20,"height":10}} | {"ok":false,"error":"RECTANGLE_BOUNDS"} |
| 接觸邊界仍有效 | {"surface":{"width":200,"height":100},"rect":{"x":100,"y":0,"width":100,"height":100}} | {"ok":true,"value":{"left":0.5,"top":0,"width":0.5,"height":1,"unit":"fraction","sourceSize":{"width":200,"height":100}}} |
在本機執行轉換
把完整例子以 JavaScript 模組在 Node.js 執行,內含純轉換函數、三個輸入及寫明的預期輸出,對不上便由斷言停止。拒絕個案回傳 ok=false 及代碼,不回傳半份統一記錄。
import assert from 'node:assert/strict';
function rectangleFractions(i){
const fail=error=>({ok:false,error});if(!i||!i.surface||!i.rect)return fail('RECTANGLE_SHAPE');
const s=i.surface,r=i.rect;
if(![s.width,s.height].every(n=>Number.isSafeInteger(n)&&n>0))return fail('SURFACE_SIZE');
if(![r.x,r.y,r.width,r.height].every(Number.isSafeInteger)||r.x<0||r.y<0||r.width<=0||r.height<=0||r.x+r.width>s.width||r.y+r.height>s.height)return fail('RECTANGLE_BOUNDS');
return {ok:true,value:{left:r.x/s.width,top:r.y/s.height,width:r.width/s.width,height:r.height/s.height,unit:'fraction',sourceSize:{width:s.width,height:s.height}}};
}
// Original synthetic cases; expected outputs are literal records.
const cases = [
{
"label": "Scale a supplied rectangle",
"input": {
"surface": {
"width": 200,
"height": 100
},
"rect": {
"x": 20,
"y": 10,
"width": 100,
"height": 40
}
},
"expected": {
"ok": true,
"value": {
"left": 0.1,
"top": 0.1,
"width": 0.5,
"height": 0.4,
"unit": "fraction",
"sourceSize": {
"width": 200,
"height": 100
}
}
}
},
{
"label": "Reject outside edge",
"input": {
"surface": {
"width": 200,
"height": 100
},
"rect": {
"x": 190,
"y": 0,
"width": 20,
"height": 10
}
},
"expected": {
"ok": false,
"error": "RECTANGLE_BOUNDS"
}
},
{
"label": "Preserve touching edges",
"input": {
"surface": {
"width": 200,
"height": 100
},
"rect": {
"x": 100,
"y": 0,
"width": 100,
"height": 100
}
},
"expected": {
"ok": true,
"value": {
"left": 0.5,
"top": 0,
"width": 0.5,
"height": 1,
"unit": "fraction",
"sourceSize": {
"width": 200,
"height": 100
}
}
}
}
];
for (const sample of cases) {
const actual = rectangleFractions(sample.input);
assert.deepEqual(actual, sample.expected);
console.log(sample.label, JSON.stringify(actual));
}
判清邊界個案
畫面 200×100,矩形 x20/y10/闊100/高40 轉成多少?
查看參考答案
left=20/200=0.1,top=10/100=0.1,width=100/200=0.5,height=40/100=0.4。終點 x120/y50,仍在來源邊界內。