Skip to content

Instantly share code, notes, and snippets.

@darekrossman
Last active August 11, 2017 13:36
Show Gist options
  • Save darekrossman/65344f07380757ee4c90 to your computer and use it in GitHub Desktop.
Save darekrossman/65344f07380757ee4c90 to your computer and use it in GitHub Desktop.
Bowling score string calculation
// 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