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
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.