This seems obvious in retrospect, but I got this from Olivier Wietrich's tag-reduce.
Tagged Literal Templates are useful syntactic sugar. I fill out a lot of school physical forms (each school has its own form), so I need strings like `Weight: ${data.wt_lb} pounds (${data.wt_kg} kg), ${data.wt_pct} percentile`
. That works fine if I am evaluating the template string when it is defined.
But I want to defer evaluating those strings until the data
array is filled in (by parsing my EMR's note, a topic for another time).
Mozilla suggests something like
function template(strings, ...keys) {
return (dict) => {
const result = [strings[0]];
keys.forEach((key, i) => {
result.push(dict[key], strings[i + 1]);
});
return result.join('');
};
}
and using as
weightTemplate = template`Weight: ${'wt_lb'} pounds (${'wt_kg'} kg), ${'wt_pct'} percentile`;
// later in code, when data dictionary is completed
finalString = weightTemplate (data);
But Olivier Wietrich suggests the much more elegant:
function template(strings, ...keys) {
return (data) => strings.reduce ( (previousValue, currentValue, currentIndex) => previousValue + data[keys[currentIndex-1]] + currentValue);
// (I'm using ECMA's parameter names for reduce, which are pretty verbose)
}
using Array.prototype.reduce
, which should have been obvious.
Using template
is the same as above.
Leave a Reply