-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stats.js
73 lines (62 loc) · 2.02 KB
/
Stats.js
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
class Stats {
/**
* Return a map for a series of games ranks by number of hands
* @param {*} games
* @returns {Map}
*/
static rankGamesByLength(games) {
return games
.slice()
.sort((a, b) => a.hands.length - b.hands.length)
.reduce((map, game, index) => {
return map.set(game.id, { hands: game.hands.length, rank: index });
}, new Map());
}
/**
* Return stats on who held the lead, and when leader changes happened for a game
* @param {*} game
* @returns
*/
static getLeaderTransistions(hands) {
let leader = 2;
let lastLeader = 2;
let lastIndex = 0;
return hands.reduce(
(result, hand, index) => {
// Index 2 is for a tied hand
leader = 2;
if (hand.counts[0] !== hand.counts[1]) {
leader = hand.counts[0] > hand.counts[1] ? 0 : 1;
}
if (leader !== lastLeader) {
//Record who the leader is and what hand it is
result.leaderChanges.push({ leader: leader, hand: index });
//Count hands since last change add to last leaders total
result.handsPerPlayer[lastLeader] += index - lastIndex;
lastIndex = index;
}
lastLeader = leader;
//Count hands between last change and end of game add to final leaders total
if (index == hands.length - 1) {
result.handsPerPlayer[leader] += hands.length - lastIndex;
}
return result;
},
{ handsPerPlayer: [0, 0, 0], leaderChanges: [] }
);
}
static getSeriesStats( games ) {
const gamesRankedByLength = this.rankGamesByLength(games);
const stats = games.reduce( (map, game, index) => {
const transitions = this.getLeaderTransistions(game.hands);
return map.set(game.id, {
hands: game.hands.length,
lengthRank: gamesRankedByLength.get(game.id).rank,
handsPerPlayer: transitions.handsPerPlayer,
leaderChanges: transitions.leaderChanges
});
}, new Map());
return stats;
}
}
module.exports = Stats;