Home > front end >  Return object using classnames and switch statement
Return object using classnames and switch statement

Time:11-26

So I have an object build out that has a bunch of methods inside, I want to be able to narrow down some methods and see if there are other ways to do thing, so I will go into more description below:

So I have the following method which returns me a bunch of class names:

function class_names() {
    return [
        'optanon-category-C0001',
        'optanon-category-C0002',
        'optanon-category-C0003',
        'optanon-category-C0004',
        'optanon-category-C0005'
    ];
}

Now I have another method which basically outputs me a string based on the classname passed inside the parameter:

function classname_output(class_name) {
    let output = '';
    switch (class_name) {
        case 'optanon-category-C0001':
            output = 'Strictly Necessary Cookies';
            break;
        case 'optanon-category-C0002':
            output = 'Performance Cookies';
            break;
        case 'optanon-category-C0003':
            output = 'Functional Cookies';
            break;
        case 'optanon-category-C0004':
            output = 'Targeting Cookies';
            break;
        case 'optanon-category-C0005':
            output = 'Social Media Cookies';
            break;
        default:
            output = 'No cookies match the specified class.';
            break;
    }

    return output;
}

Is there a way that I can infuse the two methods into a single method with an object return and then target the object key?

CodePudding user response:

You can have object (dictionary) that maps class names (key) to string (value), and then have a function to return the value if the key exists in the dictionary, or a default "Doesn't exist" string if it doesn't.

const dict = {
  'optanon-category-C0001': 'Strictly Necessary Cookies',
  'optanon-category-C0002': 'Performance Cookies',
  'optanon-category-C0003': 'Functional Cookies',
  'optanon-category-C0004': 'Targeting Cookies',
  'optanon-category-C0005': 'Social Media Cookies'
};

function check(dict, className) {
  return dict[className] ?? 'No cookies match the specified class.';
}

console.log(check(dict, 'optanon-category-C0003'));
console.log(check(dict, 'optanon-category-C0005'));
console.log(check(dict, 'optanon-category-C0000'));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Additional documentation

  • Related