Skip to the solution
MediumLow-Level DesignAsked in 20247 min read

HTML template compiler

3.7k views

The problem

Problem, as an interviewer would state it: "Write a template compiler supporting {{variable}} and {{object.path}} interpolation — compile(template) should return a fast, reusable render function, doing the expensive PARSING work only once."

Examples:

Code
const render = compile("Hello {{name}}, you are {{user.age}} years old.");
render({ name: "Ada", user: { age: 30 } }); // "Hello Ada, you are 30 years old."
render({ name: "Grace", user: { age: 45 } }); // reuses the same compiled parts

Clarifying questions expected:

  • Should parsing genuinely happen only ONCE per template, with the returned function reused efficiently across many renders?
  • What should a missing or undefined interpolation path render as — an empty string, or the literal word "undefined"?
  • Does the interpolation syntax need to support nested object paths, not just top-level variable names?

Code / implementation expected: Yes — real, direct proof that compiling happens exactly once (via a real counter) across 3 separate renders with different data, and that a missing path renders as an empty string.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: compiling happens exactly once across multiple renders (confirmed via a real counter), and a missing path renders as an empty string

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 52 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Convert Between snake_case and camelCase Object Keys (Including Nested Objects)

Continue