Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 constructor scope, and I am not pleased with that.

Is there a way to either copy a template literal without evaluating it so I can evaluate it in the right scope? Or pass the scope to the template literal?

Working error.js:

'use strict';

class Error {
    constructor(code) {
        const error = {
            //...
            //API
            1001: 'No token',
            1002: `${arguments[1]}`,
            1003: `${arguments[1]} ! ${arguments[2]}`,
            1004: 'Missing data'
            //...
        };
        let i = 0;
        this.code = code;
        this.error = error[code];
        //...
    }
}

// export default Error;
module.exports = Error;

Called like:

'use strict';
const Error = require('./error.js');

console.log(new Error(1002, 'var'));

What I would like is to be able to declare const error in the module scope, or better yet, in it's own file that I require. But doing so right now lead to argument not being the ones of the constructor, but the one of the module.

like image 836
DrakaSAN Avatar asked Jan 05 '23 04:01

DrakaSAN


1 Answers

String literals are evaluated immediately. They cannot be used as templates to be formatted later (Unlike for example Python's format strings that look similar).

You could do what Leonid Beschastny suggests and use little functions that does the interpolation for you.

Something like this:

const error = {
    1001: () => 'No token',
    1002: (args) => `${args[1]}`,
    1003: (args) => `${args[1]} ! ${args[2]}`,
    1004: () => 'Missing data'
};
this.error = error[code](arguments);
like image 66
jaap3 Avatar answered Jan 13 '23 08:01

jaap3