amar
amar

Reputation: 493

How to fill an array using class instantiation

I am learning JavaScript. I found this question online and trying to do this.

Create 2 classes "Card" and "Deck" that will represent a standard deck of 52 playing cards. Example Ace of Spades or 5 of Hearts.

Card class that takes 2 params "suit" and "rank" and stores them as public properties. Deck class has a constant array of suits[S, C, D, H]. Deck has a constant array of ranks[2,3,4,5,6,7,8,9,10,J,Q,K,A]. Deck has an empty "cards" array

On instantiation of Deck, fill the cards array with all 52 standard playing cards using the "Card" class

I did this with just the Deck class by looping over the array. But how to do it with a separate class?

class Deck {
  suits = ["S", "C", "D", "H"];
  ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"];
  constructor(suits, ranks) {
    this.suits = suits;
    this.ranks = ranks;
    this.cards = [];
  }
  getAllCards() {
    var cards = new Array();

    for (var i = 0; i < suits.length; i++) {
      for (var x = 0; x < cards.length; x++) {
        var card = {
          Value: cards[x],
          Suit: suits[i]
        };
        cards.push(card);
      }
    }
  }
  return cards;
}

Upvotes: 1

Views: 504

Answers (1)

Unmitigated
Unmitigated

Reputation: 89224

You can use a Card class instead of an object to represent each card.

class Card {
  constructor(suit, rank) {
    this.suit = suit;
    this.rank = rank;
  }
}
class Deck {
  static suits = ["S", "C", "D", "H"];
  static ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"];
  constructor() {
    this.cards = this.getAllCards();
  }
  getAllCards() {
    var cards = [];

    for (var i = 0; i < Deck.suits.length; i++) {
      for (var j = 0; j < Deck.ranks.length; j++) {
        var card = new Card(Deck.suits[i], Deck.ranks[j]);
        cards.push(card);
      }
    }
    return cards;
  }
}
console.log(new Deck().cards);

As Scott Sauyet suggests, the flatMap and map operations can also be applied for more concise code.

class Card {
  constructor(suit, rank) {
    this.suit = suit;
    this.rank = rank;
  }
}
class Deck {
  static suits = ["S", "C", "D", "H"];
  static ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"];
  constructor() {
    this.cards = Deck.suits.flatMap(suit => Deck.ranks.map(rank => new Card(suit, rank)));
  }
}
console.log(new Deck().cards);

Upvotes: 1

Related Questions