Nested Template Variable Expansion
Problem statement
Render a text template using named variables. Each row of variables is [name, value].
The template and variable values may contain two placeholder forms:
{name}inserts the fully expanded value of that variable.{name|singular|plural}requires the fully expanded value ofnameto be a non-negative integer. It inserts the number, one space, andsingularwhen the number is1; otherwise it inserts the number, one space, andplural.
Variable values may reference other variables. Expand them recursively, then render the input template.
Function
renderTemplate(text: String, variables: String[][]) → StringExamples
Example 1
text = "I like {animal}."variables = [["animal","dogs"]]return = "I like dogs."The simple placeholder is replaced by the value of animal.
Example 2
text = "Adopt {count|dog|dogs}."variables = [["count","1"]]return = "Adopt 1 dog."The numeric value is exactly 1, so the singular form is selected.
Example 3
text = "{greeting} You have {count|message|messages}."variables = [["name","Mina"],["greeting","Hello, {name}!"],["rawCount","2"],["count","{rawCount}"]]return = "Hello, Mina! You have 2 messages."Both greeting and count expand through another variable before the outer template is rendered.
Constraints
1 <= template.length <= 200000.1 <= variables.length <= 100000.- Variable names are unique and contain only ASCII letters, digits, and underscores.
- Every referenced variable exists, references are acyclic, and nesting depth is at most
1000. - Singular and plural labels are non-empty and contain no braces or
|. - The rendered output length is at most
10^6.