Interpolate a mustache-style template
Email templates, i18n strings and CMS snippets all use some flavour of {{ placeholder }}. Writing the interpolator yourself is a five-minute job that teaches you exactly why the real ones are careful about missing keys.
Implement interpolate(template, data). Replace every placeholder of the form {{ path }} — where whitespace immediately inside the braces is ignored and path is made of letters, digits, _, $ and . — with the resolved value from data.
A path is resolved by splitting on . and walking data segment by segment, so user.name reads data.user.name and items.0.title reads data.items[0].title. If the walk hits null or undefined at any point, or the final value is null or undefined, the placeholder is replaced with the empty string.
Other values are inserted with String(value), so 0 renders as "0" and false as "false". Text that is not a complete placeholder — including a {{ with no closing }} — is left exactly as it is, and inserted values are never scanned for further placeholders.
Arguments
templatestring- The template text with
{{ path }}placeholders. Whitespace inside the braces is ignored. dataobject- The object whose values resolve the placeholders. Dotted paths walk into nested objects and arrays.
Returns
string — The template with every placeholder replaced. Missing paths render as ""; inserted values are never re-scanned.
Examples
interpolate("Hello {{ name }}!", { name: "Ada" });
// => "Hello Ada!"Whitespace inside the braces is ignored.
interpolate("{{user.name}} <{{user.email}}>", {
user: { name: "Ada", email: "[email protected]" }
});
// => "Ada <[email protected]>"Dotted paths walk into nested objects.
interpolate("Hi {{missing}}{{a.b.c}}.", {});
// => "Hi ."A missing path renders as the empty string, not as undefined.
What it has to do
- Replace every
{{ path }}placeholder, ignoring whitespace inside the braces. - Resolve dotted paths, including numeric segments that index arrays.
- Replace a missing,
nullorundefinedvalue with the empty string. - Insert other values with
String(value), so0andfalserender as text. - Leave unclosed or malformed braces untouched and never re-interpolate inserted text.
Notes
- One global
.replacewith a callback is what prevents re-interpolation: the regex only looks at the original template, never at the strings the callback produced. - This interpolator does not escape the inserted values. If the output ends up in HTML you still need to combine it with an
escapeHtmlstep on each value.
Stuck? The javascript course covers everything this challenge needs.
- 1.replaces a simple placeholder ignoring inner whitespace
- 2.resolves dotted paths
- 3.indexes into arrays with numeric segments
- 4.replaces missing paths with an empty string
- 5.renders zero and false as text
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.