Last active
August 11, 2017 13:36
-
-
Save darekrossman/65344f07380757ee4c90 to your computer and use it in GitHub Desktop.
Bowling score string calculation
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
// Darek's `functional` bowling score algorithm! | |
function calculateScore(str) { | |
const rolls = str.split(''); | |
return rolls.reduce((data, roll, index) => { | |
let rollScore = calcRoll(roll, data.prevRoll); | |
if (rolls.length - index > 2) { | |
if (/(\/|X)/.test(data.prevRoll)) | |
rollScore *= 2; | |
if (/X/.test(data.prevRoll)) | |
rollScore += calcRoll(rolls[index+1], roll); | |
} | |
data.total += rollScore; | |
data.prevRoll = roll; | |
return index === rolls.length - 1 ? data.total : data; | |
}, {total: 0}); | |
} | |
function calcRoll(roll, prevRoll) { | |
return /[0-9]/.test(roll) ? parseInt(roll) : | |
/\//.test(roll) ? 10 - prevRoll : | |
/X/.test(roll) ? 10 : 0; | |
} | |
// assertions | |
console.log(calculateScore('12345123451234512345') === 60); | |
console.log(calculateScore('XXXXXXXXXXXX') === 300); | |
console.log(calculateScore('90909090909090909090') === 90); | |
console.log(calculateScore('5/5/5/5/5/5/5/5/5/5/5') === 150); | |
console.log(calculateScore('X9/X9/X9/X9/X9/X') === 200); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment