Template Fill (Strict Keys)
JavaScript
Hard
5 views
Problem Description
Line1 is a template with placeholders like {name}. Line2 is a JSON object. Replace placeholders with values. If any key is missing, print MISSING key. Else print final string.
Input Format
Line1: template string. Line2: JSON object.
Output Format
One line output.
Sample Test Case
Input:
Hello {name}, score {score}
{"name":"Ravi","score":10}
Output:
Hello Ravi, score 10
Constraints
Total length up to 2e5.
Official Solution
const fs=require('fs');const txt=fs.readFileSync(0,'utf8');const lines=txt.split(/\
?\
/);const tmpl=(lines[0]||'');const objLine=lines.slice(1).join('\
').trim();if(!tmpl.trim()||!objLine)process.exit(0);try{const o=JSON.parse(objLine);const re=/\\{([a-zA-Z_$][\\w$]*)\\}/g;let miss=null;const out=tmpl.replace(re,(m,k)=>{if(!Object.prototype.hasOwnProperty.call(o,k)){miss=k;return m;}return String(o[k]);});if(miss)throw new Error('MISSING '+miss);process.stdout.write(out);}catch(e){process.stdout.write(e.message||'MISSING');}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!