Understanding ES6 tagged template literal

229 views Asked by At

Following code snippet is used on Mozilla (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) to explain Tagged Template literal, please help me understand what following function is doing, i am unable to get the actual flow of the function, since they have used keys.foreach and when i inspected in Chrome, keys was a function, so not able to understand

function template(strings, ...keys) {
  return (function(...values) {
    var dict = values[values.length - 1] || {};
    var result = [strings[0]];
    keys.forEach(function(key, i) {
      var value = Number.isInteger(key) ? values[key] : dict[key];
      result.push(value, strings[i + 1]);
    });
    return result.join('');
  });
}

var t1Closure = template`${0}${1}${0}!`;
t1Closure('Y', 'A');  // "YAY!"
var t2Closure = template`${0} ${'foo'}!`;
t2Closure('Hello', {foo: 'World'});  // "Hello World!"
2

There are 2 answers

0
Bergi On BEST ANSWER

Most of the complexity in the example comes from the overloaded function and the forEach invocation, not from the tagged template literals. It might better have been written as two separate cases:

function dictionaryTemplate(strings, ...keys) {
  return function(dict) {
    var result = "";
    for (var i=0; i<keys.length; i++)
      result += strings[i] + dict[keys[i]];
    result += strings[i];
    return result;
  };
}
const t = dictionaryTemplate`${0} ${'foo'}!`;
t({0: 'Hello', foo: 'World'});  // "Hello World!"

function argumentsTemplate(strings, ...keys) {
  is (!keys.every(Number.isInteger))
    throw new RangeError("The keys must be integers");
  return function(...values) {
    var result = "";
    for (var i=0; i<keys.length; i++)
      result += strings[i] + values[keys[i]];
    result += strings[i];
    return result;
  };
}
const t = argumentsTemplate`${0}${1}${0}!`;
t('Y', 'A');  // "YAY!"
0
Akshay Vijay Jain On

Template is a custom function defined by us to parse the template string, whenever a function is used to parse the template string
The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.
so here specifically we have written the function to that given output
I had got confused because when in inspected keys inside the forEach, i got a function in console, but inspecting the function before forEach gave keys as the array of configurable string ${0} and ${1} in first example