先核來源與已訂規則
本例目標只容 ASCII 碼點 0 至 127,用來示範字集核對,並非完整舊編碼轉換器。「你」換問號已丟原意,所以拒收並留原文。
| 紀錄 | 輸入 JSON |
|---|---|
| 原例輸入 | {"text":"你"} |
比較兩條實際路徑
錯路把問號當已收,更正以 not-representable 暫停「你」。是否改目標編碼,要另確認對應規則。
| 路徑 | 輸出 JSON |
|---|---|
| 錯誤路徑 | {"accepted":true,"text":"?","source":"你"} |
| 更正路徑 | {"accepted":false,"error":"not-representable","source":"你"} |
import {DatabaseSync} from 'node:sqlite';
import {TextDecoder} from 'node:util';
import {inflateSync} from 'node:zlib';
import {posix} from 'node:path';
import {createHash} from 'node:crypto';
const rows=(db,sql)=>db.prepare(sql).all().map(r=>({...r}));
const failed=(action)=>{try{action();return null;}catch(e){return {code:e.errcode??e.code??e.name};}};
import assert from 'node:assert/strict';
const run=function run(i,corrected=true){
const supported=Array.from(i.text).every(c=>c.codePointAt(0)<=127);
if(corrected&&!supported)return {accepted:false,error:'not-representable',source:i.text};
return {accepted:true,text:Array.from(i.text,c=>c.codePointAt(0)<=127?c:'?').join(''),source:i.text};
};
const cases=[{"label":"misleading base","input":{"text":"你"},"expected":{"accepted":true,"text":"?","source":"你"},"corrected":false},{"label":"corrected base","input":{"text":"你"},"expected":{"accepted":false,"error":"not-representable","source":"你"},"corrected":true},{"label":"representable source","input":{"text":"Ada"},"expected":{"accepted":true,"text":"Ada","source":"Ada"},"corrected":true},{"label":"empty representable source","input":{"text":""},"expected":{"accepted":true,"text":"","source":""},"corrected":true}];
for(const test of cases){
const actual=run(test.input,test.corrected);
assert.deepEqual(actual,test.expected,test.label);
console.log(test.label,actual);
}
下次載入前核邊界
Ada 與空字串都在本例可表達範圍,照原值保留。
| 情況 | 輸入 JSON | 預期輸出 JSON |
|---|---|---|
| 可表達的英文標籤 | {"text":"Ada"} | {"accepted":true,"text":"Ada","source":"Ada"} |
| 可表達的空文字 | {"text":""} | {"accepted":true,"text":"","source":""} |
此處可否用問號代表原中文標籤?
查看參考答案
不可,這會把失真頂替當成功。原「你」留待處理,英文 Ada 則可進行。