Advertisement
kstoyanov

03. Deck of Cards

Oct 26th, 2020
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function deckOfCards(cards) {
  2.   class Card {
  3.     constructor(face, suit) {
  4.       this.face = face;
  5.       this.suit = suit;
  6.     }
  7.  
  8.     get face() {
  9.       return this._face;
  10.     }
  11.  
  12.     set face(newFace) {
  13.       const validFaces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
  14.       if (!validFaces.includes(newFace)) {
  15.         throw new Error(`Invalid card face: ${newFace}`);
  16.       }
  17.  
  18.       this._face = newFace;
  19.     }
  20.  
  21.     get suit() {
  22.       return this._suit;
  23.     }
  24.  
  25.     set suit(newSuit) {
  26.       const validSuits = ['C', 'D', 'H', 'S'];
  27.       if (!validSuits.includes(newSuit)) {
  28.         throw new Error(`Invalid card suit: ${newSuit}`);
  29.       }
  30.  
  31.       this._suit = newSuit;
  32.     }
  33.  
  34.     toString() {
  35.       const suitToChar = {
  36.         C: '\u2663',
  37.         D: '\u2666',
  38.         H: '\u2665',
  39.         S: '\u2660',
  40.       };
  41.  
  42.       return this.face + suitToChar[this.suit];
  43.     }
  44.   }
  45.  
  46.   const deck = [];
  47.   for (const cardStr of cards) {
  48.     const face = cardStr.substring(0, cardStr.length - 1);
  49.     const suit = cardStr.substr(cardStr.length - 1, 1);
  50.  
  51.     try {
  52.       deck.push(new Card(face, suit));
  53.     } catch (err) {
  54.       console.log(`Invalid card: ${cardStr}`);
  55.       return;
  56.     }
  57.   }
  58.  
  59.   console.log(deck.join(' '));
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement