\$\begingroup\$
\$\endgroup\$
3
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
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
-
1\$\begingroup\$ To further improve this answer, you can remove the
else { ... }
and simplyreturn obj[match];
\$\endgroup\$Shaun Bebbers– Shaun Bebbers2017年02月08日 16:46:42 +00:00Commented Feb 8, 2017 at 16:46
lang-js
matches
is inside method, corrected, thanks \$\endgroup\$