Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Cribbage {
- constructor(hand){
- this.hand = hand;
- this.cardsToObjs(hand);
- this.calcCombos();
- }
- get score(){
- let r = {hand: this.hand, score: 0};
- ['fifteens', 'runs', 'pairs', 'flushes', 'nobs'].forEach((x) => {
- r[x] = this[x]();
- r.score += r[x];
- });
- return r;
- }
- cardsToObjs(cards){
- this.cards = cards.split(',').map((x,i)=>{
- x = x.replace(/10/,'X');
- this.faceUpSuit = x[1];
- return {
- suit: x[1],
- faceUp: i == 4,
- rank: ' A23456789XJQK'.split('').indexOf(x[0]),
- val: ('A23456789'.split('').indexOf(x[0]) + 1) || 10
- }
- }).sort((a,b) => a.rank - b.rank);
- }
- calcCombos(){
- this.combos = [[]];
- for(let card of this.cards){
- let old = this.combos.slice();
- for(let i of old){
- this.combos.push(i.concat(card));
- }
- }
- }
- fifteens(){
- return this.combos.map((x) => x.reduce((sum,x) => sum + x.val, 0))
- .filter((x) => x == 15).length * 2;
- }
- runs(){
- return this.combos.filter((x) => {
- return x.length > 2 && x.length == x.filter((c, i, ar) =>
- i == 0 || c.rank - 1 == ar[i - 1].rank).length;
- }).map((x) => x.length).sort().filter((x,i,ar) =>
- ar[ar.length-1] == x).reduce((s,x) => s + x, 0);
- }
- pairs(){
- let hash = {};
- this.cards.forEach((x) => hash[x.rank] = (hash[x.rank] || 0) + 1);
- return Object.values(hash).map((x) => [0, 0, 2, 6, 12][x])
- .reduce((sum, x) => sum + x, 0);
- }
- flushes(){
- let hash = {};
- this.cards.forEach((x) => hash[x.suit] = (hash[x.suit] || 0) + 1);
- hash[this.faceUpSuit] < 5 && hash[this.faceUpSuit]--;
- return Object.values(hash).filter((x) => x > 3)[0] || 0;
- }
- nobs(){
- return this.cards.reduce((sum, card) =>
- sum + (card.rank == 11 && card.suit == this.faceUpSuit), 0);
- }
- }
- // Test
- console.log(
- `5D,QS,JC,KH,AC
- 8C,AD,10C,6H,7S
- AC,6D,5C,10C,8C`
- .split('\n').map((x) => new Cribbage(x).score));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement