0

Can this condition be reduced?

if (!data.type || (data.type != 'coins' && data.type != 'shop' && data.type != 'free')) 
    return socket.emit('alert_message', {
        type: 'error',
        to: '',
        message: 'Invalid purchase type'
    });

Can this be simplified so that there are no duplicate data.type? data.type must be equal to free, coins or shop

TopoR
  • 75
  • 6
  • 2
    So something like `!['coins', 'shop', 'free'].includes(data.type)`? – UnholySheep Dec 24 '21 at 00:04
  • @UnholySheep Great, otherwise I tried to use this method the other way around, it didn't work :) – TopoR Dec 24 '21 at 00:05
  • This is a micro-optimization, and introduces an albeit insignificant amount of inefficiency. Write readable code that works. Worry about minification later. – Travis J Dec 24 '21 at 00:08
  • @TravisJ I'd argue that chaining AND conditions like this is *not* readable. Especially considering they seem to be tied to operational data in the system - for example `coins` is some string that most likely exists elsewhere. It's *less* maintainable when such strings are repeated multiple times. Especially if they need to be changed and expanded. If the list of string grows to 10, for example, the `A && B && C && D && E && F && G && H && I && J` expression is much easier to introduce minor bugs, e.g., by mispelling or omitting one of the conditions. – VLAZ Dec 24 '21 at 00:13
  • @VLAZ - It is hard to tell based solely on this example. Chaining AND's a few times in a small set that wont change is fine, especially if the code is already written. If you are dealing with a mutable set, then certainly you would want a centralized place to pull that data from or manipulate it from as you are saying. Just looking at this on its face though, I don't get the impression this set is related to a scalable system. – Travis J Dec 24 '21 at 00:19
  • If we were going the centralized route, it would be ideal to use a properly authored trie lookup than using a blindly ordered list iterated using includes. – Travis J Dec 24 '21 at 00:23

0 Answers0