1
\$\begingroup\$

I have this helper method to check if 3 numbers match some of the valid results (XXX+bool, XXX, -XX, X-X, XX-, --X).

const categoryNumber = (numbers, myBool, resultNumbers) => {
  const matches = numbers.map((val, index) => val === resultNumbers[index]);
  if (matches[0] && matches[1] && matches[2] && myBool) return 1;
  if (matches[0] && matches[1] && matches[2]) return 2;
  if (matches[0] && matches[1]) return 3;
  if (matches[1] && matches[2]) return 4;
  if (matches[0] && matches[2]) return 5;
  if (matches[2]) return 6;
  return 0;
};

Type vars?:

numbers:       numeric array size 3
myBool:        boolean
resultNumbers: numeric array size 3
\$\endgroup\$
3
  • \$\begingroup\$ @m_callens my fault, matches is inside method, corrected, thanks \$\endgroup\$ – Jordi Castilla Feb 8 '17 at 15:44
  • \$\begingroup\$ have you considered using regex \$\endgroup\$ – Tolani Feb 8 '17 at 15:48
  • \$\begingroup\$ @tolani how would you do this? \$\endgroup\$ – Jordi Castilla Feb 8 '17 at 15:50
2
\$\begingroup\$

You could use a look up table, as follows:

var obj = { 'XXX': 2, '-XX': 3, 'X-X': 4, 'XX-': 5, '--X': 6}
var match = ""+ matches[0] + matches[1] + matches[2];

and then

if(match === 'XXX' && myBool){ return 1; } else { return obj[match]; }

This assumes that each position in your matches will be either an X or a -.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ To further improve this answer, you can remove the else { ... } and simply return obj[match]; \$\endgroup\$ – Shaun Bebbers Feb 8 '17 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.