This repository has been archived by the owner on Apr 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
334 lines (282 loc) · 11.3 KB
/
index.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
var bracketData = require('bracket-data')
var BracketValidator = require('bracket-validator')
var _extend = require('lodash/assign')
var _defaults = require('lodash/defaults')
var _pick = require('lodash/pick')
var _find = require('lodash/find')
var _findIndex = require('lodash/findIndex')
var _each = require('lodash/forEach')
var _map = require('lodash/map')
var _isNumber = require('lodash/isNumber')
var _isArray = require('lodash/isArray')
var _values = require('lodash/values')
var _compact = require('lodash/compact')
var _intersection = require('lodash/intersection')
var _shuffle = require('lodash/shuffle')
var _constant = function (item) {
return item
}
var allIndices = function (arr, val) {
var indices = []
var i = -1
while ((i = arr.indexOf(val, i + 1)) !== -1) {
indices.push(i)
}
return indices
}
var teamNameMatches = function (team1, team2) {
var team1Name = team1 && team1.name
var team1Names = team1 && team1.names
var team2Name = team2 && team2.name
var team2Names = team2 && team2.names
if (!_isArray(team1Name)) {
team1Name = [team1Name]
}
if (team1Names) {
team1Name = team1Name.concat(team1Names)
}
team1Name = _compact(team1Name.map(function (name) {
return typeof name === 'string' ? name.toLowerCase() : null
}))
if (!_isArray(team2Name)) {
team2Name = [team2Name]
}
if (team2Names) {
team2Name = team1Name.concat(team2Names)
}
team2Name = _compact(team2Name.map(function (name) {
return typeof name === 'string' ? name.toLowerCase() : null
}))
if (team1Name.length && team2Name.length) {
return _intersection(team1Name, team2Name).length > 0
}
return false
}
var seedMatches = function (team1, team2) {
return team1 && team2 && parseInt(team1.seed) === parseInt(team2.seed)
}
function Updater (options) {
this.bracketData = bracketData({
sport: options.sport,
year: options.year
})
this.validator = new BracketValidator({
sport: options.sport,
year: options.year
})
return this.reset(options)
}
Updater.prototype.reset = function (options) {
_defaults(options || {}, {
winner: {},
loser: {},
fromRegion: ''
})
if (typeof options.winner === 'number' || !isNaN(options.winner)) options.winner = {seed: parseInt(options.winner, 10)}
if (typeof options.loser === 'number' || !isNaN(options.loser)) options.loser = {seed: parseInt(options.loser, 10)}
if (typeof options.winner === 'string' && isNaN(options.winner)) options.winner = {name: options.winner}
if (typeof options.loser === 'string' && isNaN(options.loser)) options.loser = {name: options.loser}
// If we got passed in null or something, set the properties we need to not break
if (!options.winner) options.winner = {}
if (!options.loser) options.loser = {}
if (!options.winner.name) options.winner.name = ''
if (!options.loser.name) options.loser.name = ''
_extend(this, _pick(options, 'winner', 'loser', 'fromRegion', 'currentMaster'))
return this
}
Updater.prototype.hasWinner = function () {
return !!(this.winner && (this.winner.name || this.winner.seed))
}
Updater.prototype.hasLoser = function () {
return !!(this.loser && (this.loser.name || this.loser.seed))
}
Updater.prototype.isFinal = function () {
var finalName = this.bracketData.constants.FINAL_NAME.toLowerCase()
var finalFullname = this.bracketData.constants.FINAL_FULLNAME.toLowerCase()
var finalId = this.bracketData.constants.FINAL_ID.toLowerCase()
var region = this.fromRegion.toLowerCase()
return region === finalName || region === finalFullname || region === finalId
}
Updater.prototype.isChampionship = function () {
var championshipName = this.bracketData.constants.FINAL_CHAMPIONSHIP_NAME
return championshipName ? this.fromRegion.toLowerCase() === championshipName.toLowerCase() : false
}
Updater.prototype.teamMatches = function (team1, team2) {
if (this.isFinal()) {
return teamNameMatches(team1, team2)
}
if (team1.seed && team2.seed) {
return seedMatches(team1, team2)
}
return teamNameMatches(team1, team2)
}
Updater.prototype.gameMatches = function (winner, loser) {
return this.teamMatches(winner, this.winner) && this.teamMatches(loser, this.loser)
}
Updater.prototype.getWinnerInfo = function (winner) {
if (this.isFinal()) {
var finalTeams = this.validated[this.bracketData.constants.FINAL_ID].rounds[0]
var finalTeam = _find(finalTeams, function (team) { return teamNameMatches(team, winner) })
return {fromRegion: finalTeam.fromRegion}
} else if (winner.seed) {
return {seed: winner.seed}
} else {
return {name: winner.name, names: winner.names}
}
}
Updater.prototype.flatten = function (bracket) {
var self = this
var flattenedBracket = ''
_each(bracket, function (bracketRegion) {
var regionString = _map(bracketRegion.rounds, function (round, roundIndex) {
if (roundIndex === 0) return ''
return _map(round, function (roundGame) {
var roundValue
var pc = roundGame && (roundGame.winsIn || roundGame.playedCompetitions)
if (roundGame === null) {
return self.bracketData.constants.UNPICKED_MATCH
} else if (_isNumber(roundGame) || !isNaN(roundGame)) {
roundValue = roundGame
} else if (bracketRegion.id === self.bracketData.constants.FINAL_ID) {
roundValue = roundGame.fromRegion
} else if (roundGame.name || roundGame.names) {
var indexByName = _findIndex(bracketRegion.teams, function (t) { return teamNameMatches({name: t}, roundGame) })
roundValue = indexByName > -1 ? indexByName + 1 : null
} else {
roundValue = roundGame.seed
}
var bor = (self.bracketData.constants.BEST_OF_RANGE || []).map(function (i) { return Number(i) })
var emptyPc = !pc || bor.indexOf(Number(pc)) === -1
return roundValue.toString() + (emptyPc ? '' : pc.toString())
}).join('')
}).join('')
.replace(new RegExp(self.bracketData.order.join(''), 'g'), '')
.replace(new RegExp(_values(self.bracketData.constants.REGION_IDS).join(''), 'g'), '')
flattenedBracket += bracketRegion.id + regionString
})
return flattenedBracket
}
Updater.prototype.next = function (options, random) {
options && this.reset(options)
var bd = this.bracketData
var validated = this.validator.validate(this.currentMaster)
var randomOrder = typeof random === 'boolean' ? random : (random && random.order)
var randomWinner = typeof random === 'boolean' ? random : (random && random.winner)
var nextGame
var regionKeys = (randomOrder ? _shuffle : _constant)(bd.constants.REGION_IDS).concat(bd.constants.FINAL_ID)
_each(regionKeys, function (regionKey) {
var region = validated[regionKey]
var rounds = region.rounds
_each(rounds, function (round, roundIndex) {
var indices = allIndices(round, null)
var game = indices.length ? (randomOrder ? _shuffle : _constant)(indices)[0] : null
if (game !== null) {
nextGame = {
region: regionKey,
regionId: region.id,
round: roundIndex,
game: game
}
return false
}
return true
})
return !nextGame
})
if (nextGame) {
var prevRound = validated[nextGame.region].rounds[nextGame.round - 1]
return (randomWinner ? _shuffle : _constant)([
_extend({}, prevRound[nextGame.game * 2], {fromRegion: nextGame.regionId}),
_extend({}, prevRound[(nextGame.game * 2) + 1], {fromRegion: nextGame.regionId})
])
}
return null
}
Updater.prototype.nextRandom = function (options) {
return this.next(options, true)
}
Updater.prototype.update = function (options) {
options && this.reset(options)
var self = this
var validated = this.validator.validate(this.currentMaster)
if (validated instanceof Error) return validated
this.validated = validated
if (this.isChampionship()) {
this.fromRegion = this.bracketData.constants.FINAL_ID
}
// Looks up by id and then tries to find a match by name or fullname
var region = validated[this.fromRegion] || _find(validated, function (item) {
var fromRegion = self.fromRegion.toLowerCase()
var name = item.name && item.name.toLowerCase()
var fullname = item.fullname && item.fullname.toLowerCase()
var id = item.id && item.id.toLowerCase()
return name === fromRegion || fullname === fromRegion || id === fromRegion
})
if (!region) return new Error('No region')
if (!this.hasWinner()) return new Error('Supply at least winning team')
var regionRoundIndex = null
var nextRoundGameIndex = null
var i, ii, m, mm, round, roundGame, otherTeam
roundLoop: // eslint-disable-line no-labels
for (i = region.rounds.length; i-- > 0;) {
round = region.rounds[i]
for (ii = round.length; ii-- > 0;) {
roundGame = round[ii]
otherTeam = round[(ii % 2 === 0) ? ii + 1 : ii - 1]
if (roundGame !== null) {
if (this.hasWinner() && this.hasLoser() && this.gameMatches(roundGame, otherTeam)) {
// If we have a winner and a loser look for the game that matches both
// Place winner into the next round
regionRoundIndex = i + 1
nextRoundGameIndex = Math.floor(ii / 2)
break roundLoop // eslint-disable-line no-labels
} else {
// If there is no other team, it means we want to use the winner of the latest game they appear
// So if a user is picking a bracket, a winner can be picked without an opponent
if (this.teamMatches(roundGame, this.winner) && !this.hasLoser()) {
regionRoundIndex = i + 1
nextRoundGameIndex = Math.floor(ii / 2)
otherTeam && (this.loser = otherTeam)
break roundLoop // eslint-disable-line no-labels
}
}
}
}
}
if (regionRoundIndex !== null && nextRoundGameIndex !== null) {
var hasRound = !!region.rounds[regionRoundIndex]
if (hasRound) {
region.rounds[regionRoundIndex][nextRoundGameIndex] = _extend(this.getWinnerInfo(this.winner), _pick(options, 'playedCompetitions'))
for (i = regionRoundIndex, m = region.rounds.length; i < m; i++) {
round = region.rounds[i]
for (ii = 0, mm = round.length; ii < mm; ii++) {
roundGame = round[ii]
otherTeam = round[(ii % 2 === 0) ? ii + 1 : ii - 1]
// The losing team might have already advanced in the bracket
// Such as when someone is picking a bracket and changed their mind
// We need to remove all of the losing team from the rest of the rounds
if (this.hasLoser() && roundGame !== null && this.teamMatches(roundGame, this.loser)) {
round[ii] = null
}
}
}
}
}
// Clear losing teams from final four also
var isFinalRegion = this.fromRegion === this.bracketData.constants.FINAL_ID
if (this.hasLoser() && (!isFinalRegion || (isFinalRegion && regionRoundIndex === 1))) {
var fin = validated[this.bracketData.constants.FINAL_ID]
_each(fin.rounds, function (round, i) {
if (i > 0) {
_each(round, function (game, ii) {
if (game && teamNameMatches(game, self.loser)) {
validated[self.bracketData.constants.FINAL_ID].rounds[i][ii] = null
}
})
}
})
}
this.currentMaster = this.flatten(validated)
return this.currentMaster
}
module.exports = Updater