Passing a dynamic string to an object

Mike K :

Is it possible to somehow pass arguments to an object?

Something like,

const messages = (str1, str2){
    1: `${str1} is not the same as ${str2}`,
    2: 'message2',
    3: 'message3',
    4: 'message4',
    5: 'message5',
    6: 'message6',
}

const validateInput = ({ str1 = '', str2 = '' }) => {
    if (str1 !== str2) {
        console.log(messages[1](str1, str2))
    }
}

validateInput('a', 'b')

I'm not looking for something like,

const message = (str1, str2) => `${str1} is not the same as ${str2}`

I'm curious to know if this can be done specifically with an object.

Nina Scholz :

You could take an object for all messages and inside function which return a string with a message, depending on the handed over strings.

const messages = {
    1: (str1, str2) => `${str1} is not the same as ${str2}`,
    2: (str1, str2) => 'message2',
    3: (str1, str2) => 'message3',
    4: (str1, str2) => 'message4',
    5: (str1, str2) => 'message5',
    6: (str1, str2) => 'message6',
};

const validateInput = (str1 = '', str2 = '') => {
    if (str1 !== str2) {
        console.log(messages[1](str1, str2))
    }
}

validateInput('a', 'b');

If you switch the order of calling messages with parameters first and then by a number, then only a single function is necessary.

const messages = (str1, str2) => ({
    1: `${str1} is not the same as ${str2}`,
    2: 'message2',
    3: 'message3',
    4: 'message4',
    5: 'message5',
    6: 'message6',
});

const validateInput = (str1 = '', str2 = '') => {
    if (str1 !== str2) {
        console.log(messages(str1, str2)[1])
    }
}

validateInput('a', 'b');

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12286&siteId=1