Skip to content

Instantly share code, notes, and snippets.

@theotherzach
Last active December 25, 2015 23:59
Show Gist options
  • Save theotherzach/7060780 to your computer and use it in GitHub Desktop.
Save theotherzach/7060780 to your computer and use it in GitHub Desktop.
describe "Bowling Scorer", ->
describe "gutter game", ->
Then -> expect(game.roll(0, 20).score()).toBe(0)
describe "all 1's", ->
Then -> expect(game.roll(1, 20).score()).toBe(20)
describe "spare", ->
Then -> expect(game.roll(5, 2).roll(3).roll(0, 17).score()).toBe(16)
describe "strike", ->
Then -> expect(game.roll(10).roll(3).roll(4).roll(0, 16).score()).toBe(24)
describe "perfect game", ->
Then -> expect(game.roll(10, 22).score()).toBe(300)
(function () {
function game(initialRolls, currentFrame) {
return {
roll: game.roll,
score: game.score,
_rolls: initialRolls || initializeRolls(),
_currentFrame: currentFrame || 0
};
}
game.roll = function (pins, numberOfRolls) {
var i,
rolls = _.clone(this._rolls);
currentFrame = this._currentFrame;
if (numberOfRolls === undefined) { numberOfRolls = 1; }
for (i = 0; i < numberOfRolls; i += 1) {
rolls[currentFrame] = pins;
currentFrame += 1;
}
return game(rolls, currentFrame);
};
game.score = function () {
var i,
frameIndex = 0,
result = 0,
rolls = this._rolls;
for (i = 0; i < 10; i += 1) {
if(isStrike(frameIndex, rolls)) {
result += scoreStrikeFrame(frameIndex, rolls);
frameIndex += 1;
} else if(isSpare(frameIndex, rolls)) {
result += scoreSpareFrame(frameIndex, rolls);
frameIndex += 2;
} else {
result += scoreOpenFrame(frameIndex, rolls);
frameIndex += 2;
}
}
return result;
};
function isStrike(frameIndex, rolls) {
return rolls[frameIndex] === 10;
}
function scoreStrikeFrame(frameIndex, rolls) {
return 10 + rolls[frameIndex + 1] + rolls[frameIndex + 2];
}
function isSpare(frameIndex, rolls) {
return rolls[frameIndex] + rolls[frameIndex + 1] === 10;
}
function scoreSpareFrame(frameIndex, rolls) {
return 10 + rolls[frameIndex + 2];
}
function scoreOpenFrame(frameIndex, rolls) {
return rolls[frameIndex] + rolls[frameIndex + 1];
}
function initializeRolls() {
var i, rolls = [];
for (i = 0; i < 22; i += 1) {
rolls[i] = 0;
}
return rolls;
}
window.game = game();
})();
@theotherzach
Copy link
Author

Well, not really fluent since I'm returning a new object in each step of the chain rather than mutating the underlying one. The code is considerably uglier than the canonical bowling kata, but the API is pretty rad.

This API

game.roll(5, 2).roll(3).roll(0, 17).score()

vs the canonical API

this.game = new Game
this.game.roll(5, 2)
this.game.roll(3)
this.game.roll(0, 17)
this.game.score()

@theotherzach
Copy link
Author

Oops. Just noticed that I forgot the "use strict"; at the top of the containing function in fluent-bowling.js

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