1

I'm building a 'Deck' class, modeled after a standard deck of playing cards.

What I WANT is an array of 52 cards, with every possible combination of suits and ranks.

What I GET is an array of length 4, each element of which is an array of 13 objects.

CODE:

ranks = [1..13]                                                                                                                       
suits = ["S", "H", "D", "C"]          

cards = ({rank: rank, suit: suit} for rank in ranks for suit in suits)

Now I know that I can get the job done by declaring an empty array and pushing to it with each iteration, but that doesn't seem as elegant as using the return value of the for. (This is a pet project, so just getting it to work is not the only goal.)

What is the elegant solution here? How do I get the for statement to return a flat array of each combination of cards?

1 Answer 1

2

How about:

cards = [].concat ({rank: rank, suit: suit} for rank in ranks for suit in suits)...
Sign up to request clarification or add additional context in comments.

2 Comments

Hm.. that still leaves 'cards' with length 4, on my version of coffeescript.. (v1.7.1)
Oh, wait.. I didn't notice the '...'. This is interesting. It does work, so thanks for the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.