ES6 Template Literals: How to pass a scope before they are interpreted?

后端 未结 3 357
清酒与你
清酒与你 2021-01-01 04:36

I am starting to use template literals to make a error generator.

I have working code, but I am forced to declare the list of possible errors inside the constr

3条回答
  •  伪装坚强ぢ
    2021-01-01 04:47

    My preferred solution to pass scope is using this wrapper:

    function defer([fisrt, ...rest]) {
      return (...values) => rest.reduce((acc, str, i) => acc + values[i] + str, fisrt);
    }
    

    That's all. When I want to reuse a template and defer the resolution of the substitutions, I just do:

    > t = defer`My template is: ${null} and ${null}`;
    > t('simple', 'reusable');          // 'My template is: simple and reusable'
    > t('obvious', 'late to the party'; // 'My template is: obvious and late to the party'
    > t(null);                          // 'My template is: null and undefined'
    >
    > defer`Choose: ${'ignore'} / ${undefined}`(true, false); // 'Choose: true / false'
    

    Applying this tag returns back a 'function' (instead of a 'string') that ignores any parameters passed to the literal. Then it can be called with new parameters later. If a parameter has no corresponding replace, it becomes 'undefined'.

    You can find more information in those other answers: this and that.

提交回复
热议问题