String interpolation - more Stackoverflow love
Continuing on my blog on useful gems of code from stackoverflow, is this beautiful function which does string interpolation. I just renamed it and reproduced it here.
const stringInterpolate = function(str, params) {
const names = Object.keys(params);
const vals = Object.values(params);
return new Function(...names, `return \`${str}\`;`)(...vals);
}
Why do we need this when Javascript has template literals. Template literals are useful only in literal context of code. What if we have a template string, which is used to display multiple rows of data, say an object array, or from a database fetch. It is good to have this method as part of your helper methods while displaying dynamic content. See example below
const db_data = [
{ name: "David", age: 10 },
{ name: "John", age: 20 },
{ name: "Kate", age: 25 }
]
const details_template = "Student ${name} aged ${age} years.";
for(const d of db_data) {
console.log(stringInterpolate(details_template, d));
}
// Outputs the three lines
// Student David aged 10 years.
// Student John aged 20 years.
// Student Kate aged 25 years.