來源格式與預期記錄
這是原創假設轉換例子。輸入限下列欄位的普通、無循環 JSON 形記錄,統一記錄格式及拒絕代碼由本例訂明。若換來源,先修改格式約定。
本例用正整數位置作物件欄名,不能有前置零。每項有貨品字樣及非負安全整數數量。按數字位置排序,輸出仍列原位置;沒有的號碼不補記錄。slots 為空便得到空清單。
| 個案 | 輸入記錄(JSON) | 預期輸出(JSON) |
|---|---|---|
| 保留原位置 | {"slots":{"1":{"item":"A","units":0},"3":{"item":"C","units":2}}} | {"ok":true,"value":{"lines":[{"slot":1,"item":"A","units":0},{"slot":3,"item":"C","units":2}]}} |
| 拒絕負件數 | {"slots":{"1":{"item":"A","units":-1}}} | {"ok":false,"error":"SLOT_LINE"} |
| 保留沒有項目 | {"slots":{}} | {"ok":true,"value":{"lines":[]}} |
在本機執行轉換
把完整例子以 JavaScript 模組在 Node.js 執行,內含純轉換函數、三個輸入及寫明的預期輸出,對不上便由斷言停止。拒絕個案回傳 ok=false 及代碼,不回傳半份統一記錄。
import assert from 'node:assert/strict';
function repeatingSlots(i){
const fail=error=>({ok:false,error});if(!i||!i.slots||typeof i.slots!=='object'||Array.isArray(i.slots))return fail('SLOT_OBJECT');
const lines=[];
for(const [key,r]of Object.entries(i.slots)){
const slot=Number(key);if(!/^[1-9]\d*$/.test(key)||!Number.isSafeInteger(slot))return fail('SLOT_POSITION');
if(!r||typeof r.item!=='string'||!r.item||!Number.isSafeInteger(r.units)||r.units<0)return fail('SLOT_LINE');
lines.push({slot,item:r.item,units:r.units});
}
lines.sort((a,b)=>a.slot-b.slot);return {ok:true,value:{lines}};
}
// Original synthetic cases; expected outputs are literal records.
const cases = [
{
"label": "Keep source slots",
"input": {
"slots": {
"1": {
"item": "A",
"units": 0
},
"3": {
"item": "C",
"units": 2
}
}
},
"expected": {
"ok": true,
"value": {
"lines": [
{
"slot": 1,
"item": "A",
"units": 0
},
{
"slot": 3,
"item": "C",
"units": 2
}
]
}
}
},
{
"label": "Reject negative quantity",
"input": {
"slots": {
"1": {
"item": "A",
"units": -1
}
}
},
"expected": {
"ok": false,
"error": "SLOT_LINE"
}
},
{
"label": "Preserve empty slots",
"input": {
"slots": {}
},
"expected": {
"ok": true,
"value": {
"lines": []
}
}
}
];
for (const sample of cases) {
const actual = repeatingSlots(sample.input);
assert.deepEqual(actual, sample.expected);
console.log(sample.label, JSON.stringify(actual));
}
判清邊界個案
來源只有位置 1、3,是否要補位置 2 的空白行?
查看參考答案
不用。先列位置 1 的 A=0,再列位置 3 的 C=2。空號保留,來源明確提供的零數量行也保留。