'Check within 3 variables that 3 specified values are held, in any order but not doubled up

I'm trying to code a function into my card game to check if the first 2 cards hold any 2 out of the following 3 values: 6, 7 or 8 i.e. 6&7, 7&8, or 6&8.

For the sake of being specific: I don't want it to return true if its 2 of the same value but I imagine that could be done with a && card1Value!==card2Value added onto the conditions of the logical statement.

From there I'll then need to make it so that card3Value is checked for the missing value.



Solution 1:[1]

I'd personally split that up a little:

function threeCardsAreValid(card1, card2, card3) {

 if(!twoCardsAreValid(card1, card2)) return false
 if (cardIs6Or7Or8(card3) && card3 !== card1 && card3!== card2) return true
 return false
}

function twoCardsAreValid(card1, card2) {

 if (cardIs6Or7Or8(card1) && cardIs6Or7Or8(card2) && card1 !== card2) {
  return true
 }
 return false

}

function cardIs6Or7Or8(card) {
 return (card === 6 | card === 7 | card === 8)
}

Solution 2:[2]

What I would personnaly go for is filtering the array and creating a set to see if there are no duplicates.

Then, if the result array has a length greater than 2, then at least 2 of the 3 cards are valid.

function checkHand(card1, card2, card3){
  const arr = [card1,card3,card2]
  const validHands = [6,7,8]
  
  const validHandsFilteredWithoutDuplicates =  [...new Set(arr.filter(x => validHands.includes(x)))]
  
  return validHandsFilteredWithoutDuplicates.length >= 2
}

console.log(checkHand(6,7,9)) // true
console.log(checkHand(1,2,3)) // false
console.log(checkHand(7,7,4)) // false
console.log(checkHand(6,7,8)) // true

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 RenaudC5