Overview 🔍
Tagged Functions, also known as Tagged Template Literals, are an advanced feature of template literals introduced in ES6 (2015). They enable more control over how template literals are processed, allowing for custom formatting, parsing, or even validation.
One popular use case for tagged template literals is in GraphQL for building query strings dynamically.
Syntax
Definition
A tagged template literal is a combination of a "tag function" and a template literal. The tag function receives the literal's strings and interpolated values as arguments, enabling custom processing.
Here’s a basic example:
const bar = "var bar";
function tag(strings, ...values) {
console.log(strings); // Array of string literals
console.log(values); // Array of interpolated values
}
Usage
tag`foo ${bar} baz`;
// Output:
// ['foo ', ' baz'] // Array of strings
// ['var bar'] // Array of values
Use Cases
1. Internationalization (i18n)
Tagged template literals can be used to process strings dynamically for localization.
Example:
function i18n(strings, ...values) {
const translations = {
"Hello, ": "Hola, "
};
return strings.reduce((acc, str, i) => {
const translatedStr = translations[str] || str; // Translate if possible
return acc + translatedStr + (values[i] || '');
}, '');
}
const name = "Alice";
const result = i18n`Hello, ${name}!`;
console.log(result);
// Output: "Hola, Alice!"
2. GraphQL
In GraphQL, tagged template literals are widely used to define and manipulate query strings.
Example:
const query = gql`
query {
user(id: 1) {
name
age
}
}
`;
3. Handling Arguments with Tagged Template Literals
Tagged template literals can also process arguments by passing an additional value to the tag function and applying functions within the template literal.
Example:
function tagged(baseValue) {
return function(strings, ...functions) {
return strings.reduce((acc, str, i) => {
const value = typeof functions[i] === 'function' ? functions[i](baseValue) : '';
return acc + str + value;
}, '');
};
}
const result = tagged(2)`foo${n => n * 0}bar${n => n * 1}baz${n => n * 2}`;
console.log(result);
// Output:
// "foo0bar2baz4"
Discussion and Insights 💭
Tagged template literals enable dynamic string processing with custom logic, making them ideal for use cases like query building, internationalization, and input sanitization. They improve code readability and maintainability, especially in scenarios requiring advanced string manipulation.
Top comments (0)