Elegant way to generate string from tagged template?

Glen Huang curvedmark at gmail.com
Tue Dec 23 05:29:40 PST 2014

Thanks for the suggestion.

You inspired me to realize that the basic idea shouldn’t be to find a way to intersperse two arrays, but to find a way to undo the tagging of template.

so `template` === tag`template`, where tag = (templateObj, …args) => untag(templateObj, …args)

If you intend to put the templateObj back together into a string eventually (which i guess most tagging functions do), this kind of action should be very common.

Since the target (templateObj) is an array, I think the method should belong to Array, and it should behave like a join, but instead of joining array items with a string, it joins with many strings. Maybe something like Array.prototype.interspersedJoin (much like your String.default):

[1,2,3].interspersedJoin(“a”, “b”) = “1a2b3”
[1,2,3].interspersedJoin(“a”) = “1a23”
[1,2,3].interspersedJoin(“a”,”b”,”c”) = “1a2b3c”

And for the tag function:

function tag(templateObj, …args) {
	return templateObj.interspersedJoin(...args);

> On Dec 23, 2014, at 8:34 PM, Gary Guo <nbdd0121 at hotmail.com> wrote:
> > From: curvedmark at gmail.com <mailto:curvedmark at gmail.com>
> > Date: Tue, 23 Dec 2014 14:55:57 +0800
> >
> > Given an array of [1,2,3] and other array of [“a”,”b”], it should return [1,”a”,2,“b”,3]. (probably a lot of edge cases to cover, but just ignore them for now).
> I came up with an idea. Symmetric to String.raw, we can have a function that represents the default procedure.
> ```js
> String.default=(a,...b)=>{
>     let ret="";
>     for(let i=0;ret+=a[i],i<b.length;ret+=b[i],i++);
>     return ret;
> };
> ```
> So in semantics, String.default `Template` === `Template`. By introducing this, we can define a common procedure between tagged and untagged templates: untagged templates are equivalent to the tagged ones with tag String.default.
> When implementing our own template functions, we can use:
> ```js
> function custom(template, ...substitutions){
>     // Perform actions on substitutions or template
>     return String.default(template, ...substitutions);
> }
> ```

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20141223/3fbb6665/attachment.html>

More information about the es-discuss mailing list