Hacker News new | past | comments | ask | show | jobs | submit login

It creates a function returning a function, where the argument to the first (which is a template) is used as a closure in the second (which takes a dict of values).

The last function called in turn creates a function using the Function constructor, which, since it takes a string argument as the function body, allows the expansion of the values dict into variables and thus the population of the template string:

applyTemplate("aaa ${v}")({"v":"yo"}) --> "aaa yo"




How come you haven't used tagged template literals? These would fit this use case: https://codeburst.io/javascript-es6-tagged-template-literals...


It's not my code :) However, tagged template literals won't allow dict expansion the way this solution does. Also, a template literal is evaluated at the time of assignment. This will allow you to re-use an arbitrary template string with any matching values:

  tpl = applyTemplate("Hello ${a}");
  tpl({"a": "you"}); // --> Hello you
  tpl({"a": "dude"});  // --> Hello dude


You did a better job of explaining my code than I would have done! Thank you.


Thanks! My pleasure :-)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: