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
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Feb 8, 2017 at 15:30
\$\endgroup\$
3
  • \$\begingroup\$ @m_callens my fault, matches is inside method, corrected, thanks \$\endgroup\$ Commented Feb 8, 2017 at 15:44
  • \$\begingroup\$ have you considered using regex \$\endgroup\$ Commented Feb 8, 2017 at 15:48
  • \$\begingroup\$ @tolani how would you do this? \$\endgroup\$ Commented Feb 8, 2017 at 15:50

1 Answer 1

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 -.

answered Feb 8, 2017 at 16:40
\$\endgroup\$
1
  • 1
    \$\begingroup\$ To further improve this answer, you can remove the else { ... } and simply return obj[match]; \$\endgroup\$ Commented Feb 8, 2017 at 16:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.