Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function HandScorer() {
- function score(hand) {
- var matches = {},
- handByNumber = matchingNumbers(hand),
- handBySuit = matchingSuits(hand);
- scorers.forEach(function (scorer) {
- scorer(hand, handByNumber, handBySuit, matches);
- });
- return matches;
- }
- var matchingNumbers = matcherBuilder(function (card) {
- return card.number()
- });
- var matchingSuits = matcherBuilder(function (card) {
- return card.suit()
- });
- var fourOfAKind = nOfNumber(4, 'four of a kind');
- var threeOfAKind = nOfNumber(3, '3 of a kind');
- var twoOfAKind = nOfNumber(2, '2 of a kind');
- var onePair = nOfNumber(2, '2 of a kind');
- var fullHouse = function (hand, handByNumber, handByType, matches) {
- if (matches['three of a kind'].length && matches['three of a kind'].length) {
- matches['full house'] = {
- 'three of a kind': matches['three of a kind'],
- 'two of a kind': matches['two of a kind']
- }
- }
- };
- var straight = function (hand, handByNumber, handByType, matches) {
- var sequential = [];
- var previous;
- Object.keys(handByNumber).map(function (number) {
- return parseInt(number)
- }).sort()
- .forEach(function (number) {
- if (previous && (previous + 1) == number) {
- sequential.push(number)
- } else {
- sequential = [number]
- }
- previous = number;
- });
- return matches['straight'] = sequential;
- };
- var flush = function (hand, handByNumber, handBySuit, matches) {
- return matches['flush'] = Object.keys(handBySuit).reduce(function (matching, card) {
- if (handBySuit[card] == 5) {
- matching.push(card)
- }
- }, [])
- };
- function nOfNumber(n, name) {
- return function (hand, handByNumber, handByType, matches) {
- matches[name] = Object.keys(handByNumber).reduce(function (matching, card) {
- if (handByNumber[card] == n) {
- matching.push(card)
- }
- }, [])
- }
- }
- function matcherBuilder(criteriaResolver) {
- return function (hand) {
- return hand
- .map(criteriaResolver)
- .reduce(function (matches, card) {
- matches[card] = (matches[card] || 0) + 1;
- return matches;
- }, {});
- }
- }
- var scorers = [fourOfAKind, threeOfAKind, twoOfAKind, onePair, fullHouse, straight, flush];
- return {score: score}
- }
- HandScorer.types = {
- ROYAL_FLUSH: 'royal flush',
- STRAIGHT_FLUSH: 'straight flush',
- FOUR: 'four of a kind',
- FULL_HOUSE: 'full house',
- FLUSH: 'flush',
- STRAIGHT: 'straight',
- THREE: 'three of a kind',
- TWO: 'two of a kind',
- ONE: 'one of a kind',
- HIGH: 'high card'
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement