有一个enum类型:
enum HandRank {
HighCard;
OnePair;
Set;
TwoPair;
Straight;
Flush;
FullHouse;
Quads;
StraightFlush;
RoyalFlush;
}
我想比较一对值来选择一个更好的。比如:
maxRank = <...some method...>(firstRank, secondRank) ? firstRank : secondRank;
在这里,我假设enum的所有值都以优先升序跟随。我该怎么解决这个问题呢?
你可以这样做:
maxRank = Type.enumIndex(firstRank) > Type.enumIndex(secondRank) ? firstRank : secondRank;
我将这样写一个Max函数:
class HandRanks {
public static function toInt (a:HandRank) return switch a {
case HighCard: 1;
case OnePair: 2;
case Set: 3;
case TwoPair: 4;
case Straight: 5;
case Flush: 6;
case FullHouse: 7;
case Quads: 8;
case StraightFlush: 9;
case RoyalFlush: 10;
}
public static function max (a:HandRank, b:HandRank) {
var a1 = toInt(a);
var b1 = toInt(b);
return if (a1 > b1) a else b;
}
}
// usage
using HandRanks;
HighCard.max(Set); // Set