Source contract and expected records
This is an original, fully synthetic mapping example. Inputs are plain, acyclic JSON-shaped records with the fields shown; the canonical shape and rejection codes belong to this example. Adapt the contract before using a different source.
The original grammar uses | between labels and backslash to escape either | or backslash itself. No other escape is allowed. Empty whole text means no labels; empty segments, unknown escapes and a trailing backslash are rejected. Preserve label text after decoding, including spaces and repeated labels.
| Case | Input record (JSON) | Expected output (JSON) |
|---|---|---|
| Decode literal separator | {"labels":"fragile\\|blue|heavy"} | {"ok":true,"value":{"labels":["fragile|blue","heavy"]}} |
| Reject undefined escape | {"labels":"a\\q"} | {"ok":false,"error":"LABEL_ESCAPE"} |
| Preserve empty label set | {"labels":""} | {"ok":true,"value":{"labels":[]}} |
Run the local transformation
Run the complete example as a JavaScript module in Node.js. It contains the pure mapping function, all three inputs and literal expected outputs; assertions stop on a mismatch. A rejected case returns ok=false with an error code, rather than a partial canonical record.
import assert from 'node:assert/strict';
function escapedLabels(i){
const fail=error=>({ok:false,error});if(!i||typeof i.labels!=='string')return fail('LABEL_STRING');
if(i.labels==='')return {ok:true,value:{labels:[]}};
const labels=[];let value='',escaped=false;
for(const ch of i.labels){
if(escaped){if(ch!=='|'&&ch!=='\\')return fail('LABEL_ESCAPE');value+=ch;escaped=false;}
else if(ch==='\\')escaped=true;
else if(ch==='|'){if(!value)return fail('EMPTY_LABEL');labels.push(value);value='';}
else value+=ch;
}
if(escaped)return fail('DANGLING_ESCAPE');if(!value)return fail('EMPTY_LABEL');labels.push(value);
return {ok:true,value:{labels}};
}
// Original synthetic cases; expected outputs are literal records.
const cases = [
{
"label": "Decode literal separator",
"input": {
"labels": "fragile\\|blue|heavy"
},
"expected": {
"ok": true,
"value": {
"labels": [
"fragile|blue",
"heavy"
]
}
}
},
{
"label": "Reject undefined escape",
"input": {
"labels": "a\\q"
},
"expected": {
"ok": false,
"error": "LABEL_ESCAPE"
}
},
{
"label": "Preserve empty label set",
"input": {
"labels": ""
},
"expected": {
"ok": true,
"value": {
"labels": []
}
}
}
];
for (const sample of cases) {
const actual = escapedLabels(sample.input);
assert.deepEqual(actual, sample.expected);
console.log(sample.label, JSON.stringify(actual));
}
Work through the boundary
How many labels does the first case contain?
Show the worked answer
Two: fragile|blue and heavy. The escaped pipe belongs inside the first label. The unescaped pipe separates the labels; a backslash before q returns LABEL_ESCAPE.