Last active
October 19, 2016 06:40
-
-
Save peteroid/09681ca2134f8e14a822af90c58bee5a to your computer and use it in GitHub Desktop.
This file contains 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
var getTenPinBowlingScore = function (result) { | |
// construct the array from string | |
var resultArr = result.split(',').map(s => { | |
return parseInt(s) | |
}) | |
var calculatedResult = resultArr.reduce((preVal, curVal, curIdx, arr) => { | |
// calcualte any extra score | |
if (preVal.extraCounts) { | |
preVal.currentFrameScore += (curVal * preVal.extraCounts.length) | |
preVal.extraCounts = preVal.extraCounts.map(c => { | |
return c - 1 | |
}).filter(c => { | |
return c > 0 | |
}) | |
} | |
// determine the frame | |
if (preVal.isNewFrame) { | |
preVal.tempFrameCount++ | |
// add a new frame | |
preVal.tempFrameCount <= 10 && preVal.frames.push([]) | |
// strike: extra score for next 2 falls | |
preVal.isNewFrame = (curVal == 10 && preVal.tempFrameCount <= 10) | |
preVal.isNewFrame && preVal.extraCounts.push(2) | |
} else { | |
preVal.isNewFrame = true | |
// spare: extra score for next fall | |
curVal + arr[curIdx - 1] == 10 && preVal.extraCounts.push(1) | |
} | |
preVal.currentFrameScore += curVal | |
preVal.frames[preVal.frames.length - 1].push(curVal) | |
// add the frame score to the total score | |
if (preVal.isNewFrame || (curIdx == arr.length - 1)) { | |
preVal.totalScore += Math.min(30, preVal.currentFrameScore) | |
preVal.currentFrameScore = 0 | |
} | |
return preVal | |
}, { | |
totalScore: 0, | |
currentFrameScore: 0, | |
isNewFrame: true, | |
tempFrameCount: 0, | |
frames: [], | |
extraCounts: [] | |
}) | |
console.log("Frames for %s\nis %s", result, JSON.stringify(calculatedResult.frames)) | |
return calculatedResult.totalScore | |
} | |
var test = function (test, expected) { | |
console.log("Testing %d, expecting %d", test, expected) | |
console.log((test === expected ? "Passed" : "Failed") + "\n") | |
} | |
test(getTenPinBowlingScore('10,10,10,10,10,10,10,10,10,10,10,10'), 300) | |
test(getTenPinBowlingScore('1,2,3,4,5,5'), 20) | |
test(getTenPinBowlingScore('9,1,10,8,0,2'), 48) | |
test(getTenPinBowlingScore('10,0,0,9,1,0,0,8,2,0,0,7,3,0,0,6,4,0,0'), 50) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expected result:
Tested with
Node v6.1.0