Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. class Cribbage {
  2.  
  3. constructor(hand){
  4. this.hand = hand;
  5. this.cardsToObjs(hand);
  6. this.calcCombos();
  7. }
  8.  
  9. get score(){
  10. let r = {hand: this.hand, score: 0};
  11. ['fifteens', 'runs', 'pairs', 'flushes', 'nobs'].forEach((x) => {
  12. r[x] = this[x]();
  13. r.score += r[x];
  14. });
  15. return r;
  16. }
  17.  
  18. cardsToObjs(cards){
  19. this.cards = cards.split(',').map((x,i)=>{
  20. x = x.replace(/10/,'X');
  21. this.faceUpSuit = x[1];
  22. return {
  23. suit: x[1],
  24. faceUp: i == 4,
  25. rank: ' A23456789XJQK'.split('').indexOf(x[0]),
  26. val: ('A23456789'.split('').indexOf(x[0]) + 1) || 10
  27. }
  28. }).sort((a,b) => a.rank - b.rank);
  29. }
  30.  
  31. calcCombos(){
  32. this.combos = [[]];
  33. for(let card of this.cards){
  34. let old = this.combos.slice();
  35. for(let i of old){
  36. this.combos.push(i.concat(card));
  37. }
  38. }
  39. }
  40.  
  41. fifteens(){
  42. return this.combos.map((x) => x.reduce((sum,x) => sum + x.val, 0))
  43. .filter((x) => x == 15).length * 2;
  44. }
  45.  
  46. runs(){
  47. return this.combos.filter((x) => {
  48. return x.length > 2 && x.length == x.filter((c, i, ar) =>
  49. i == 0 || c.rank - 1 == ar[i - 1].rank).length;
  50. }).map((x) => x.length).sort().filter((x,i,ar) =>
  51. ar[ar.length-1] == x).reduce((s,x) => s + x, 0);
  52. }
  53.  
  54. pairs(){
  55. let hash = {};
  56. this.cards.forEach((x) => hash[x.rank] = (hash[x.rank] || 0) + 1);
  57. return Object.values(hash).map((x) => [0, 0, 2, 6, 12][x])
  58. .reduce((sum, x) => sum + x, 0);
  59. }
  60.  
  61. flushes(){
  62. let hash = {};
  63. this.cards.forEach((x) => hash[x.suit] = (hash[x.suit] || 0) + 1);
  64. hash[this.faceUpSuit] < 5 && hash[this.faceUpSuit]--;
  65. return Object.values(hash).filter((x) => x > 3)[0] || 0;
  66. }
  67.  
  68. nobs(){
  69. return this.cards.reduce((sum, card) =>
  70. sum + (card.rank == 11 && card.suit == this.faceUpSuit), 0);
  71. }
  72.  
  73. }
  74.  
  75.  
  76. // Test
  77. console.log(
  78. `5D,QS,JC,KH,AC
  79. 8C,AD,10C,6H,7S
  80. AC,6D,5C,10C,8C`
  81. .split('\n').map((x) => new Cribbage(x).score));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement