Created
July 27, 2022 00:27
-
-
Save arthursvpb/5fc1a1b5e366766003671084509a5b50 to your computer and use it in GitHub Desktop.
Bowling Score Calculator written in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const score1 = '165/251/X2/71XX1/7'; | |
const score2 = '12324/XX9/247/X9/0'; | |
const score3 = '6/54X6/367/X9/278/X'; | |
function calculateScore(input) { | |
const scoreArray = input.split(''); | |
const calculateSlashBonus = (previous, next) => 10 - previous + next; | |
const calculateXBonus = (next, nextNext) => 10 + next + nextNext; | |
const isFinalRound = index => index > 15; | |
const scoreMap = scoreArray.map((score, index, array) => { | |
const previousPrevious = +array[index - 2]; | |
const previous = array[index - 1] === '/' ? 10 - previousPrevious : +array[index - 1]; | |
const next = array[index + 1] === 'X' ? 10 : +array[index + 1]; | |
const nextNext = array[index + 2] === '/' ? 10 - next : +array[index + 2]; | |
// Special final round | |
if (isFinalRound(index)) { | |
if (score === '/') return 10 - previous; | |
if (score === 'X') return 10; | |
return +score; | |
} | |
if (score === '/') return calculateSlashBonus(previous, next); | |
if (score === 'X') return calculateXBonus(next, nextNext); | |
return +score; | |
}); | |
const scoreTotal = scoreMap.reduce((prev, curr) => prev + curr); | |
return scoreTotal; | |
} | |
console.log(`Score 1: ${calculateScore(score1)}`); | |
console.log(`Score 2: ${calculateScore(score2)}`); | |
console.log(`Score 3: ${calculateScore(score3)}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment