|
| 1 | +// This problem involves playing cards: https://en.wikipedia.org/wiki/Standard_52-card_deck |
| 2 | + |
| 3 | +// Implement a function getCardValue, when given a string representing a playing card, |
| 4 | +// should return the numerical value of the card. |
| 5 | + |
| 6 | +// A valid card string will contain a rank followed by the suit. |
| 7 | +// The rank can be one of the following strings: |
| 8 | +// "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" |
| 9 | +// The suit can be one of the following emojis: |
| 10 | +// "♠", "♥", "♦", "♣" |
| 11 | +// For example: "A♠", "2♥", "10♥", "J♣", "Q♦", "K♦". |
| 12 | + |
| 13 | +// When the card is an ace ("A"), the function should return 11. |
| 14 | +// When the card is a face card ("J", "Q", "K"), the function should return 10. |
| 15 | +// When the card is a number card ("2" to "10"), the function should return its numeric value. |
| 16 | + |
| 17 | +// When the card string is invalid (not following the above format), the function should |
| 18 | +// throw an error. |
| 19 | + |
| 20 | +// Acceptance criteria: |
| 21 | +// After you have implemented the function, write tests to cover all the cases, and |
| 22 | +// execute the code to ensure all tests pass. |
| 23 | + |
| 24 | +function getCardValue(card) { |
| 25 | + |
| 26 | +} |
| 27 | + |
| 28 | + |
| 29 | +// The line below allows us to load the getCardValue function into tests in other files. |
| 30 | +// This will be useful in the "rewrite tests with jest" step. |
| 31 | +module.exports = getCardValue; |
| 32 | + |
| 33 | +// Helper functions to make our assertions easier to read. |
| 34 | +function assertEquals(actualOutput, targetOutput) { |
| 35 | + console.assert( |
| 36 | + actualOutput === targetOutput, |
| 37 | + `Expected ${actualOutput} to equal ${targetOutput}` |
| 38 | + ); |
| 39 | +} |
| 40 | + |
| 41 | +// TODO: Write tests to cover all outcomes, including throwing errors for invalid cards. |
| 42 | +// Examples 1 numbers: |
| 43 | +assertEquals(getCardValue("9♠"), 9); |
| 44 | + |
| 45 | + |
| 46 | +function assertThrow(fn){ |
| 47 | +try { (fn) |
| 48 | + // we try to run this function, if it throws, stop running this bit and run the catch below |
| 49 | + |
| 50 | + // This line will not be reached if an error is thrown as expected |
| 51 | + console.error("Error was not thrown for invalid card"); |
| 52 | +} catch (error) { |
| 53 | + // if the above code throws, we catch the error here, that stops the whole program crashing |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | +// What other invalid card cases can you think of? |
| 58 | + |
| 59 | +//Examples wrong type: |
| 60 | +assertThrow(()=>getCardValue("null")) |
| 61 | +assertThrow(()=>getCardValue("42")) |
0 commit comments