-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbowling.js
More file actions
84 lines (66 loc) · 1.93 KB
/
Copy pathbowling.js
File metadata and controls
84 lines (66 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
'use strict';
var Bowling = function () {};
Bowling.prototype.result = function (rolls) {
this.rolls = this.getFrames(rolls.split(''));
return this.getScore();
};
Bowling.prototype.getScore = function () {
var accumulator, currentFrame, nextFrame, isStrike, isSpare;
var score = 0;
for (var i = 0; i < this.rolls.length; i++) {
if (i > 9)
break;
currentFrame = this.rolls[i];
nextFrame = this.rolls[i + 1];
accumulator = 0;
isStrike = this.isStrike(currentFrame[0]);
isSpare = this.isSpare(currentFrame[1]);
if (isStrike || isSpare) {
if (nextFrame)
accumulator = this.getAccumulatorScore(isStrike, isSpare, nextFrame);
score += (10 + accumulator);
continue;
}
score += currentFrame[1] ? currentFrame[0] + currentFrame[1] : currentFrame[0];
}
return score;
};
Bowling.prototype.getFrames = function (rolls) {
var singleFrame = [];
var totalFrames = [];
for (var i = 0; i < rolls.length; i++) {
singleFrame.push(this.checkScoreType(rolls[i]));
if (i % 2 !== 0 && i !== 0 || i === rolls.length - 1) {
totalFrames.push(singleFrame);
singleFrame = [];
}
}
return totalFrames;
};
Bowling.prototype.getAccumulatorScore = function (isStrike, isSpare, nextFrame) {
var accumulator = 0;
var isStrikeOnNextFrame = this.isStrike(nextFrame[0]);
if (isStrikeOnNextFrame)
return accumulator = 10;
if (isStrike)
return accumulator = nextFrame[0] + nextFrame[1];
if (isSpare)
return accumulator = nextFrame[0];
};
Bowling.prototype.checkScoreType = function (score) {
if (this.isSpare(score))
return '/';
if (this.isStrike(score))
return 'X';
if (score === '-')
return 0;
if (typeof score === 'string')
return parseInt(score, 10);
};
Bowling.prototype.isStrike = function (input) {
return input === 'X';
};
Bowling.prototype.isSpare = function (input) {
return input === '/';
};
module.exports = Bowling;