Template String Interpolation
MediumP3Coding
Implement interpolate(template, data), which replaces {{path}} placeholders in a string with values from data.
- A placeholder is
{{, a path,}}. Spaces around the path are ignored:{{ user.name }}equals{{user.name}}. - A path is dot-separated keys, with optional array indexes:
user.name,items[0].title,items.0.title. - The replacement is
String(value), so0becomes"0"andfalsebecomes"false". - If the path does not exist, or the value is
nullorundefined, the placeholder becomes the empty string. - Text that is not a complete placeholder (an unclosed
{{, a single brace) is left unchanged. Replaced values are not scanned again for placeholders. - Never evaluate code; only read properties.
Example 1
- Input
- interpolate('Hi {{ user.name }}, you have {{count}} items', { user: { name: 'Ada' }, count: 3 })
- Output
- 'Hi Ada, you have 3 items'
Constraints
- 0 <= template.length <= 10^5
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 11. ⌘Enter runs, ⌘⇧Enter submits.