Skip to content

Instantly share code, notes, and snippets.

@peteroid
Last active October 19, 2016 06:40
Show Gist options
  • Save peteroid/09681ca2134f8e14a822af90c58bee5a to your computer and use it in GitHub Desktop.
Save peteroid/09681ca2134f8e14a822af90c58bee5a to your computer and use it in GitHub Desktop.
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)
@peteroid
Copy link
Author

Expected result:

Frames for 10,10,10,10,10,10,10,10,10,10,10,10
is [[10],[10],[10],[10],[10],[10],[10],[10],[10],[10,10,10]]
Testing 300, expecting 300
Passed

Frames for 1,2,3,4,5,5
is [[1,2],[3,4],[5,5]]
Testing 20, expecting 20
Passed

Frames for 9,1,10,8,0,2
is [[9,1],[10],[8,0],[2]]
Testing 48, expecting 48
Passed

Frames for 10,0,0,9,1,0,0,8,2,0,0,7,3,0,0,6,4,0,0
is [[10],[0,0],[9,1],[0,0],[8,2],[0,0],[7,3],[0,0],[6,4],[0,0]]
Testing 50, expecting 50
Passed

Tested with Node v6.1.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment