Files
JS/01_grundlagen/projekte/js-basics-royal-flush-template/index.js
Philippe Torrel 8b439649b5
2026-06-26 15:05:09 +02:00

83 lines
2.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const SUITS = '♠♥♦♣';
const NAMES = [
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'J',
'Q',
'K',
'A',
];
// Arbeitsschritt 1: Prüfung auf Name und Kartenfarbe
const toName = (card) => {
// Bei '10' sind die ersten 2 Zeichen der Name, sonst das erste Zeichen
return card.startsWith('10') ? '10' : card[0];
};
const toSuit = (card) => card[card.length - 1];
// Arbeitsschritt 2: Validierung
const isValidCard = (card) => {
const name = toName(card);
const suit = toSuit(card);
return NAMES.includes(name) && SUITS.includes(suit);
};
const isValidHand = (hand) => {
return Array.isArray(hand) && hand.length === 5 && hand.every(isValidCard);
};
// Arbeitsschritt 3: Sortierung
const sortHand = (hand) => {
const compareCards = (cardA, cardB) => {
const nameIndexA = NAMES.indexOf(toName(cardA));
const nameIndexB = NAMES.indexOf(toName(cardB));
const suitIndexA = SUITS.indexOf(toSuit(cardA));
const suitIndexB = SUITS.indexOf(toSuit(cardB));
// Kartenposition = Gewichtungsfaktor × Position des Namens + Position der Kartenfarbe
const positionA = SUITS.length * nameIndexA + suitIndexA;
const positionB = SUITS.length * nameIndexB + suitIndexB;
return positionA - positionB;
};
return [...hand].sort(compareCards);
};
// Arbeitsschritt 4: Kategorisierung
const isFlush = (hand) => {
if (!isValidHand(hand)) return false;
const suits = hand.map(toSuit);
return suits.every((suit) => suit === suits[0]);
};
const isStraight = (hand) => {
if (!isValidHand(hand)) return false;
const sortedHand = sortHand(hand);
const names = sortedHand.map(toName);
const namesString = names.join(',');
const allNamesString = NAMES.join(',');
return allNamesString.includes(namesString);
};
const isStraightFlush = (hand) => {
return isStraight(hand) && isFlush(hand);
};
const isRoyalFlush = (hand) => {
if (!isStraightFlush(hand)) return false;
const sortedHand = sortHand(hand);
const names = sortedHand.map(toName);
// Royal Flush muss mit 10 beginnen und mit A enden
return names[0] === '10' && names[4] === 'A';
};