...` operator (template literal spreads)

Template literal strings are almost useful. Here is how you can co-opt splat syntax to make template strings work the way that some people would prefer that it worked.

foo(1, ...``, 2);
foo(1, ...`${a}`, 2);
foo(1, ...`${a}${b}`, 2);
foo(1, ...`Hello ${a} there ${b} world`, 2);
// syntax sugar for =>
foo(1, '', 2);
foo(1, a, 2); // as opposed to foo(1, '', a, '', 2);
foo(1, a, b, 2); // as opposed to foo(1, '', a, '', b, '', 2);
foo(1, "Hello ", a, " there ", b, " world", 2);

...`something` is syntax sugar for ...internal_splat_helper`something` :

const internal_splat_helper = (template, ...rest) => {
	if (template.length === 1)
		return template;
	const ret = [];
	let i = 0;
	for (; i < rest.length; ++i) {
		if (template[i] !== '')
			ret.push(template[i]);
		ret.push(rest[i]);
	}
	if (template[i] !== '')
		ret.push(template[i]);
	return ret;
};

That's already valid syntax, foo(...`bar`) is effectively foo(..."bar") is foo("b", "a", "r").

Besides, that ...splat`something` form looks workable, it's not that long and doesn't require learning another language feature.

1 Like