| 8 | 8 | * @param {string} category |
| 9 | 9 | * @returns {number} |
| 10 | 10 | */ |
| 11 | | export const score = () => { |
| 12 | | throw new Error('Remove this line and implement the function'); |
| 11 | export const score = (dices, category) => { |
| 12 | // Edge Case: Invalid number of dice |
| 13 | if (dices.length !== 5) { |
| 14 | return 0; |
| 15 | } |
| 16 | |
| 17 | // Edge Case: Invalid dice values (not between 1-6) |
| 18 | for (let die of dices) { |
| 19 | if (die < 1 || die > 6) { |
| 20 | return 0; |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | // Count occurrences of each die value |
| 25 | const counts = {}; |
| 26 | for (let die of dices) { |
| 27 | counts[die] = (counts[die] || 0) + 1; |
| 28 | } |
| 29 | |
| 30 | // Get sorted dice for straight checks |
| 31 | const sortedDice = [...dices].sort((a, b) => a - b); |
| 32 | |
| 33 | switch (category) { |
| 34 | case 'ones': |
| 35 | return (counts[1] || 0) * 1; |
| 36 | |
| 37 | case 'twos': |
| 38 | return (counts[2] || 0) * 2; |
| 39 | |
| 40 | case 'threes': |
| 41 | return (counts[3] || 0) * 3; |
| 42 | |
| 43 | case 'fours': |
| 44 | return (counts[4] || 0) * 4; |
| 45 | |
| 46 | case 'fives': |
| 47 | return (counts[5] || 0) * 5; |
| 48 | |
| 49 | case 'sixes': |
| 50 | return (counts[6] || 0) * 6; |
| 51 | |
| 52 | case 'full house': |
| 53 | // Edge Case: Check if there are exactly two different numbers, one appearing 3 times and the other 2 times |
| 54 | const countValues = Object.values(counts); |
| 55 | if (countValues.length === 2 && countValues.includes(3) && countValues.includes(2)) { |
| 56 | return dices.reduce((sum, die) => sum + die, 0); |
| 57 | } |
| 58 | return 0; |
| 59 | |
| 60 | case 'four of a kind': |
| 61 | // Edge Case: Check if at least one die appears 4 or more times |
| 62 | for (let die in counts) { |
| 63 | if (counts[die] >= 4) { |
| 64 | return parseInt(die) * 4; |
| 65 | } |
| 66 | } |
| 67 | return 0; |
| 68 | |
| 69 | case 'little straight': |
| 70 | // Edge Case: Check if dice form sequence 1-2-3-4-5 |
| 71 | if (sortedDice.join('') === '12345') { |
| 72 | return 30; |
| 73 | } |
| 74 | return 0; |
| 75 | |
| 76 | case 'big straight': |
| 77 | // Edge Case: Check if dice form sequence 2-3-4-5-6 |
| 78 | if (sortedDice.join('') === '23456') { |
| 79 | return 30; |
| 80 | } |
| 81 | return 0; |
| 82 | |
| 83 | case 'choice': |
| 84 | return dices.reduce((sum, die) => sum + die, 0); |
| 85 | |
| 86 | case 'yacht': |
| 87 | // Edge Case: Check if all dice show the same face |
| 88 | if (Object.values(counts).includes(5)) { |
| 89 | return 50; |
| 90 | } |
| 91 | return 0; |
| 92 | |
| 93 | default: |
| 94 | return 0; |
| 95 | } |
| 96 | |
| 97 | // Handled Edge Cases: invalid number of dice, invalid dice values, full house validation, four of a kind validation, little straight validation, big straight validation, yacht validation |
| 13 | 98 | }; |