juanmorschrott
juanmorschrott

Reputation: 603

Which pattern would you use to solve that kind of expression?

I have multiple states and multiple values, and well, I can use a function, else if logic, but want to know your opinion about which design pattern or implementation is better for this kind of casuistry:

item.status == 'upcoming' ? 
     'label-upcoming' : 
        ( item.type == 'ticket_required' && 
            item.status == 'available' && 
              item.hasTicket == true ? 
                 'label-ticket' : '')

I don´t want a solution, just learn some technics. Thanks in advance

Upvotes: 0

Views: 758

Answers (2)

Bergi
Bergi

Reputation: 664970

Since you incorporate multiple conditions for item.status here, an object literal that is immediately looked up might be handy:

({
  'upcoming': 'label-upcoming',
  'available': item.type == 'ticket_required' && item.hasTicket && 'label-ticket'
}[item.status] || '')

(though in this case it's quite ugly as you have a complex expression inside the object, which also has to be evaluated every time even if the key is not picked, and the defaulting from there to '' is hard to understand). Nonetheless it's a pattern you should know :-) To make it more performant, put the object literal in a static place to avoid creating new objects. If you need it more flexible, put in functions instead of keys:

// Using ES6 syntax for conciseness, works with ES5 function expression just as well
const lookup = {
  'upcoming': (_) => 'label-upcoming',
  'available': (item) => item.type == 'ticket_required' && item.hasTicket ? 'label-ticket' : ''
};

… (lookup[item.status] || (_)=>'')(item) …

And of course, you can always use an IIFE:

… (function() {
    switch(item.status) {
        case 'upcoming':  return 'label-upcoming';
        case 'available': if (item.type == 'ticket_required' && item.hasTicket)
                              return 'label-ticket';
        default: return '';
    }
}()) …

Upvotes: 4

Axel Amthor
Axel Amthor

Reputation: 11106

That's compact but hard to read, I would prefer "if-else" for maintainability.

Upvotes: 1

Related Questions