带你读《现代TypeScript高级教程》十八、TS实战之扑克牌排序(3)https://developer.aliyun.com/article/1348419?groupCode=tech_library
完整的函数如下所示:
export function handRank( cardStrings: [string, string, string, string, string]): Hand { const cards: Card[] = cardStrings.map((str: string) => ({ rank: rankToNumber( str.substring(0, str.length - 1) as Rank ), suit: suitToNumber(str.at(-1) as Suit) })); // We won't use the [0] place in the following arrays const countBySuit = new Array(5).fill(0); const countByRank = new Array(15).fill(0); const countBySet = new Array(5).fill(0); cards.forEach((card: Card) => { countByRank[card.rank]++; countBySuit[card.suit]++; }); countByRank.forEach( (count: number) => count && countBySet[count]++ ); // count the A also as a 14, for straights countByRank[14] = countByRank[1]; if (countBySet[4] === 1 && countBySet[1] === 1) return Hand.FourOfAKind; else if (countBySet[3] && countBySet[2] === 1) return Hand.FullHouse; else if (countBySet[3] && countBySet[1] === 2) return Hand.ThreeOfAKind; else if (countBySet[2] === 2 && countBySet[1] === 1) return Hand.TwoPairs; else if (countBySet[2] === 1 && countBySet[1] === 3) return Hand.OnePair; else if (countBySet[1] === 5) { if (countByRank.join('').includes('11111')) return !countBySuit.includes(5) ? Hand.Straight : countByRank.slice(10).join('') === '11111' ? Hand.RoyalFlush : Hand.StraightFlush; else { /* !countByRank.join("").includes("11111") */ return countBySuit.includes(5) ? Hand.Flush : Hand.HighCard; } } else { throw new Error( 'Unknown hand! This cannot happen! Bad logic!' ); }}
测试代码
console.log(handRank(['3♥', '5♦', '8♣', 'A♥', '6♠'])); // 0console.log(handRank(['3♥', '5♦', '8♣', 'A♥', '5♠'])); // 1console.log(handRank(['3♥', '5♦', '3♣', 'A♥', '5♠'])); // 2console.log(handRank(['3♥', '5♦', '8♣', '5♥', '5♠'])); // 3console.log(handRank(['3♥', '2♦', 'A♣', '5♥', '4♠'])); // 4console.log(handRank(['J♥', '10♦', 'A♣', 'Q♥', 'K♠'])); // 4console.log(handRank(['3♥', '4♦', '7♣', '5♥', '6♠'])); // 4console.log(handRank(['3♥', '4♥', '9♥', '5♥', '6♥'])); // 5console.log(handRank(['3♥', '5♦', '3♣', '5♥', '3♠'])); // 6console.log(handRank(['3♥', '3♦', '3♣', '5♥', '3♠'])); // 7console.log(handRank(['3♥', '4♥', '7♥', '5♥', '6♥'])); // 8console.log(handRank(['K♥', 'Q♥', 'A♥', '10♥', 'J♥'])); // 9
在线运行