Compile a template once into a reusable render function
A notification service sends the same message templates thousands of times with different values. Parsing the template on every send is wasted work, so templates are compiled once into a render function that can be called many times.
Implement compileTemplate(template). It returns a function render(values) that fills in the template’s placeholders.
const render = compileTemplate(template);
render(values); // => string
TypeError if template is not a string.render function. Each call to render is independent, and render can be called any number of times.{{, optional spaces, a key, optional spaces, then }}. So {{name}} and {{ name }} are both placeholders for name._ or $, followed by letters, digits, _ or $. Keys are case-sensitive.{{ 1st }}, {{ user.name }}, {{ first name }} or {{}}) is plain text and is copied unchanged.String(values[key]) when values has an own property key whose value is not null or undefined.values may be omitted, null or undefined. Then every placeholder is kept.values is not modified.const shipped = compileTemplate('Hi {{ name }}, order #{{orderId}} ships {{ day }}.');
shipped({ name: 'Mei', orderId: 4821, day: 'Monday' });
// => 'Hi Mei, order #4821 ships Monday.'
shipped({ name: 'Leo', orderId: 0 });
// => 'Hi Leo, order #0 ships {{ day }}.'
shipped();
// => 'Hi {{ name }}, order #{{orderId}} ships {{ day }}.'
compileTemplate('{{ greeting }} {{ user.name }}')({ greeting: 'Hey {{ x }}', x: 'no' });
// => 'Hey {{ x }} {{ user.name }}'
compileTemplate(42); // throws TypeError