3 // No frameworks, no compilers, no npm, just JavaScript. :-)
6 let global_filters = {};
7 let next_filterset_id = 2; // Arbitrary IDs are fine as long as they never collide.
9 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
10 addEventListener('click', possibly_close_menu);
11 fetch('ultimate.json')
12 .then(response => response.json())
13 .then(response => { global_json = response; process_matches(global_json, global_filters); });
15 function format_time(t)
17 const ms = t % 1000 + '';
18 t = Math.floor(t / 1000);
19 const sec = t % 60 + '';
20 t = Math.floor(t / 60);
21 const min = t % 60 + '';
22 const hour = Math.floor(t / 60) + '';
23 return hour + ':' + min.padStart(2, '0') + ':' + sec.padStart(2, '0') + '.' + ms.padStart(3, '0');
26 function attribute_player_time(player, to, from, offense) {
28 if (player.on_field_since > from) {
29 // Player came in while play happened (without a stoppage!?).
30 delta_time = to - player.on_field_since;
32 delta_time = to - from;
34 player.playing_time_ms += delta_time;
35 if (offense === true) {
36 player.offensive_playing_time_ms += delta_time;
37 } else if (offense === false) {
38 player.defensive_playing_time_ms += delta_time;
42 function take_off_field(player, t, live_since, offense, keep) {
44 if (live_since === null) {
45 // Play isn't live, so nothing to do.
47 attribute_player_time(player, t, live_since, offense);
49 if (player.on_field_since !== null) { // Just a safeguard; out without in should never happen.
50 player.field_time_ms += t - player.on_field_since;
53 player.on_field_since = null;
56 function add_cell(tr, element_type, text) {
57 let element = document.createElement(element_type);
58 element.textContent = text;
59 tr.appendChild(element);
63 function add_th(tr, text, colspan) {
64 let element = document.createElement('th');
65 let link = document.createElement('a');
66 link.style.cursor = 'pointer';
67 link.addEventListener('click', (e) => {
69 process_matches(global_json, global_filters);
71 link.textContent = text;
72 element.appendChild(link);
73 tr.appendChild(element);
76 element.setAttribute('colspan', colspan);
78 element.setAttribute('colspan', '3');
83 function add_3cell(tr, text, cls) {
84 let p1 = add_cell(tr, 'td', '');
85 let element = add_cell(tr, 'td', text);
86 let p2 = add_cell(tr, 'td', '');
88 p1.classList.add('pad');
89 p2.classList.add('pad');
90 if (cls === undefined) {
91 element.classList.add('num');
93 element.classList.add(cls);
98 function add_3cell_with_filler_ci(tr, text, cls) {
99 let element = add_3cell(tr, text, cls);
101 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
102 svg.classList.add('fillerci');
103 svg.setAttribute('width', ci_width);
104 svg.setAttribute('height', ci_height);
105 element.appendChild(svg);
110 function add_3cell_ci(tr, ci) {
112 add_3cell_with_filler_ci(tr, 'N/A');
117 if (ci.format === 'percentage') {
118 text = (100 * ci.val).toFixed(0) + '%';
120 text = ci.val.toFixed(2);
122 let element = add_3cell(tr, text);
123 let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
126 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
127 if (ci.inverted === true) {
128 svg.classList.add('invertedci');
130 svg.classList.add('ci');
132 svg.setAttribute('width', ci_width);
133 svg.setAttribute('height', ci_height);
135 // The good (green) and red (bad) ranges.
136 let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
137 s0.classList.add('range');
138 s0.classList.add('s0');
139 s0.setAttribute('width', to_x(ci.desired));
140 s0.setAttribute('height', ci_height);
141 s0.setAttribute('x', '0');
143 let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
144 s1.classList.add('range');
145 s1.classList.add('s1');
146 s1.setAttribute('width', ci_width - to_x(ci.desired));
147 s1.setAttribute('height', ci_height);
148 s1.setAttribute('x', to_x(ci.desired));
151 let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
152 bar.classList.add('bar');
153 bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
154 bar.setAttribute('height', ci_height / 3);
155 bar.setAttribute('x', to_x(ci.lower_ci));
156 bar.setAttribute('y', ci_height / 3);
158 // Marker line for average.
159 let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
160 marker.classList.add('marker');
161 marker.setAttribute('x1', to_x(ci.val));
162 marker.setAttribute('x2', to_x(ci.val));
163 marker.setAttribute('y1', ci_height / 6);
164 marker.setAttribute('y2', ci_height * 5 / 6);
168 svg.appendChild(bar);
169 svg.appendChild(marker);
171 element.appendChild(svg);
174 function calc_stats(json, filters) {
176 for (const player of json['players']) {
177 players[player['player_id']] = {
178 'name': player['name'],
179 'gender': player['gender'],
180 'number': player['number'],
196 'playing_time_ms': 0,
197 'offensive_playing_time_ms': 0,
198 'defensive_playing_time_ms': 0,
202 'offensive_points_completed': 0,
203 'offensive_points_won': 0,
204 'defensive_points_completed': 0,
205 'defensive_points_won': 0,
207 'offensive_soft_plus': 0,
208 'offensive_soft_minus': 0,
209 'defensive_soft_plus': 0,
210 'defensive_soft_minus': 0,
217 'last_point_seen': null,
218 'on_field_since': null,
223 players['globals'] = {
225 'playing_time_ms': 0,
226 'offensive_playing_time_ms': 0,
227 'defensive_playing_time_ms': 0,
230 'offensive_points_completed': 0,
231 'offensive_points_won': 0,
232 'defensive_points_completed': 0,
233 'defensive_points_won': 0,
235 let globals = players['globals'];
237 for (const match of json['matches']) {
238 if (!keep_match(match['match_id'], filters)) {
245 let handler_got_by_interception = false; // Only relevant if handler !== null.
246 let prev_handler = null;
247 let live_since = null;
248 let offense = null; // True/false/null (unknown).
250 let pull_started = null;
251 let last_pull_was_ours = null; // Effectively whether we're playing an O or D point (not affected by turnovers).
253 let game_started = null;
254 let last_goal = null;
256 // The last used formations of the given kind, if any; they may be reused
257 // when the point starts, if nothing else is set.
258 let last_offensive_formation = null;
259 let last_defensive_formation = null;
261 // Formations we've set, but haven't really had the chance to use yet
262 // (e.g., we get a “use zone defense” event while we're still on offense).
263 let pending_offensive_formation = null;
264 let pending_defensive_formation = null;
266 // Formations that we have played at least once this point, after all
267 // heuristics and similar.
268 let formations_used_this_point = new Set();
270 for (const [q,p] of Object.entries(players)) {
271 p.on_field_since = null;
272 p.last_point_seen = null;
274 for (const e of match['events']) {
276 let type = e['type'];
277 let p = players[e['player']];
280 let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
281 if (type === 'in' && p.on_field_since === null) {
282 p.on_field_since = t;
283 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
284 // A player needed for the filters went onto the field,
285 // so pretend people walked on right now (to start their
287 for (const [q,p2] of Object.entries(players)) {
288 if (p2.on_field_since !== null) {
289 p2.on_field_since = t;
293 } else if (type === 'out') {
294 take_off_field(p, t, live_since, offense, keep);
295 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
296 // A player needed for the filters went off the field,
297 // so we need to attribute time for all the others.
298 // Pretend they walked off and then immediately on again.
300 // TODO: We also need to take care of this to get the globals right.
301 for (const [q,p2] of Object.entries(players)) {
302 if (p2.on_field_since !== null) {
303 take_off_field(p2, t, live_since, offense, keep);
304 p2.on_field_since = t;
310 keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters); // Recompute after in/out.
312 // Liveness management
313 if (type === 'pull' || type === 'their_pull' || type === 'restart') {
315 } else if (type === 'catch' && last_pull_was_ours === null) {
316 // Someone forgot to add the pull, so we'll need to wing it.
317 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
319 last_pull_was_ours = !offense;
320 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
321 for (const [q,p] of Object.entries(players)) {
322 if (p.on_field_since === null) {
325 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
327 // In case the player did nothing this point,
328 // not even subbing in.
329 p.last_point_seen = point_num;
333 if (keep) attribute_player_time(p, t, live_since, offense);
335 if (type !== 'stoppage') {
337 if (last_pull_was_ours === true) { // D point.
338 ++p.defensive_points_completed;
339 if (type === 'goal') {
340 ++p.defensive_points_won;
342 } else if (last_pull_was_ours === false) { // O point.
343 ++p.offensive_points_completed;
344 if (type === 'goal') {
345 ++p.offensive_points_won;
353 if (type !== 'stoppage') {
355 ++globals.points_played;
356 if (last_pull_was_ours === true) { // D point.
357 ++globals.defensive_points_completed;
358 if (type === 'goal') {
359 ++globals.defensive_points_won;
361 } else if (last_pull_was_ours === false) { // O point.
362 ++globals.offensive_points_completed;
363 if (type === 'goal') {
364 ++globals.offensive_points_won;
368 if (live_since !== null) {
369 globals.playing_time_ms += t - live_since;
370 if (offense === true) {
371 globals.offensive_playing_time_ms += t - live_since;
372 } else if (offense === false) {
373 globals.defensive_playing_time_ms += t - live_since;
382 if (type === 'goal') {
384 } else if (type === 'their_goal') {
388 // Point count management
389 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
391 p.last_point_seen = point_num;
395 if (type === 'goal' || type === 'their_goal') {
399 if (type !== 'out' && game_started === null) {
404 if (type === 'pull') {
405 puller = e['player'];
408 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
409 // No effect on pull.
410 } else if (type === 'pull_landed' && puller !== null) {
411 if (keep) players[puller].pull_times.push(t - pull_started);
412 } else if (type === 'pull_oob' && puller !== null) {
413 if (keep) ++players[puller].oob_pulls;
415 // Not pulling (if there was one, we never recorded its outcome, but still count it).
416 puller = pull_started = null;
419 // Offense/defense management
420 let last_offense = offense;
421 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
423 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
426 if (last_offense !== offense && live_since !== null) {
427 // Switched offense/defense status, so attribute this drive as needed,
428 // and update live_since to take that into account.
430 for (const [q,p] of Object.entries(players)) {
431 if (p.on_field_since === null) {
434 attribute_player_time(p, t, live_since, last_offense);
436 globals.playing_time_ms += t - live_since;
437 if (offense === true) {
438 globals.offensive_playing_time_ms += t - live_since;
439 } else if (offense === false) {
440 globals.defensive_playing_time_ms += t - live_since;
446 if (type === 'pull') {
447 last_pull_was_ours = true;
448 } else if (type === 'their_pull') {
449 last_pull_was_ours = false;
450 } else if (type === 'set_offense' && last_pull_was_ours === null) {
451 // set_offense could either be “changed to offense for some reason
452 // we could not express”, or “we started in the middle of a point,
453 // and we are offense”. We assume that if we already saw the pull,
454 // it's the former, and if not, it's the latter; thus, the === null
455 // test above. (It could also be “we set offense before the pull,
456 // so that we get the right button enabled”, in which case it will
457 // be overwritten by the next pull/their_pull event anyway.)
458 last_pull_was_ours = false;
459 } else if (type === 'set_defense' && last_pull_was_ours === null) {
461 last_pull_was_ours = true;
462 } else if (type === 'goal' || type === 'their_goal') {
463 last_pull_was_ours = null;
466 // Formation management
467 if (type === 'formation_offense' || type === 'formation_defense') {
468 let id = e.formation === null ? 0 : e.formation;
469 let for_offense = (type === 'formation_offense');
470 if (offense === for_offense) {
471 formations_used_this_point.add(id);
472 } else if (for_offense) {
473 pending_offensive_formation = id;
475 pending_defensive_formation = id;
478 last_offensive_formation = id;
480 last_defensive_formation = id;
482 } else if (last_offense !== offense) {
483 if (offense === true && pending_offensive_formation !== null) {
484 formations_used_this_point.add(pending_offensive_formation);
485 pending_offensive_formation = null;
486 } else if (offense === false && pending_defensive_formation !== null) {
487 formations_used_this_point.add(pending_defensive_formation);
488 pending_defensive_formation = null;
489 } else if (offense === true && last_defensive_formation !== null) {
490 if (should_reuse_last_formation(match['events'], t)) {
491 formations_used_this_point.add(last_defensive_formation);
493 } else if (offense === false && last_offensive_formation !== null) {
494 if (should_reuse_last_formation(match['events'], t)) {
495 formations_used_this_point.add(last_offensive_formation);
500 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
501 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
503 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
504 // The handler subbed out and was replaced with another handler,
505 // so this wasn't a pass.
510 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
511 // Self-pass to goal after an interception; this is not a real pass,
512 // just how we represent a Callahan right now -- so don't
513 // count the throw, any assists or similar.
515 // It's an open question how we should handle a self-pass that is
516 // _not_ after an interception, or a self-pass that's not a goal.
517 // (It must mean we tipped off someone.) We'll count it as a regular one
518 // for the time being, although it will make hockey assists weird.
521 handler = prev_handler = null;
522 } else if (type === 'catch' || type === 'goal') {
523 if (handler !== null) {
525 ++players[handler].num_throws;
530 if (keep) ++p.touches;
531 if (type === 'goal') {
533 if (prev_handler !== null) {
534 ++players[prev_handler].hockey_assists;
536 if (handler !== null) {
537 ++players[handler].assists;
541 handler = prev_handler = null;
543 // Update hold history.
544 prev_handler = handler;
545 handler = e['player'];
546 handler_got_by_interception = false;
548 } else if (type === 'throwaway') {
553 handler = prev_handler = null;
554 } else if (type === 'drop') {
556 handler = prev_handler = null;
557 } else if (type === 'stallout') {
558 if (keep) ++p.stallouts;
559 handler = prev_handler = null;
560 } else if (type === 'was_d') {
561 if (keep) ++p.was_ds;
562 handler = prev_handler = null;
563 } else if (type === 'defense') {
564 if (keep) ++p.defenses;
565 } else if (type === 'interception') {
572 handler = e['player'];
573 handler_got_by_interception = true;
574 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
576 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
577 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
578 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
579 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
580 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
581 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
582 type !== 'formation_offense' && type !== 'formation_defense') {
583 console.log(format_time(t) + ": Unknown event “" + e + "”");
586 if (type === 'goal' || type === 'their_goal') {
587 formations_used_this_point.clear();
591 // Add field time for all players still left at match end.
592 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
594 for (const [q,p] of Object.entries(players)) {
595 if (p.on_field_since !== null && last_goal !== null) {
596 p.field_time_ms += last_goal - p.on_field_since;
599 if (game_started !== null && last_goal !== null) {
600 globals.field_time_ms += last_goal - game_started;
602 if (live_since !== null && last_goal !== null) {
603 globals.playing_time_ms += last_goal - live_since;
604 if (offense === true) {
605 globals.offensive_playing_time_ms += last_goal - live_since;
606 } else if (offense === false) {
607 globals.defensive_playing_time_ms += last_goal - live_since;
615 function process_matches(json, filtersets) {
616 let chosen_category = get_chosen_category();
617 write_main_menu(chosen_category);
619 let filterset_values = Object.values(filtersets);
620 if (filterset_values.length === 0) {
621 filterset_values = [[]];
625 for (const filter of filterset_values) {
626 let players = calc_stats(json, filter);
628 if (chosen_category === 'general') {
629 rows = make_table_general(players);
630 } else if (chosen_category === 'offense') {
631 rows = make_table_offense(players);
632 } else if (chosen_category === 'defense') {
633 rows = make_table_defense(players);
634 } else if (chosen_category === 'playing_time') {
635 rows = make_table_playing_time(players);
636 } else if (chosen_category === 'per_point') {
637 rows = make_table_per_point(players);
642 let merged_rows = [];
643 if (filterset_values.length > 1) {
644 for (let i = 0; i < rowsets.length; ++i) {
645 let marker = make_filter_marker(filterset_values[i]);
647 // Make filter header.
648 let tr = rowsets[i][0];
649 let th = document.createElement('th');
651 tr.insertBefore(th, tr.firstChild);
653 for (let j = 1; j < rowsets[i].length; ++j) {
654 let tr = rowsets[i][j];
656 // Remove the name for cleanness.
658 tr.firstChild.nextSibling.textContent = '';
662 tr.style.borderTop = '0px';
664 if (i != rowsets.length - 1) {
665 tr.style.borderBottom = '0px';
668 // Make filter marker.
669 let td = document.createElement('td');
670 td.textContent = marker;
671 td.classList.add('filtermarker');
672 tr.insertBefore(td, tr.firstChild);
676 for (let i = 0; i < rowsets[0].length; ++i) {
677 for (let j = 0; j < rowsets.length; ++j) {
678 merged_rows.push(rowsets[j][i]);
679 if (i === 0) break; // Don't merge the headings.
683 merged_rows = rowsets[0];
685 document.getElementById('stats').replaceChildren(...merged_rows);
688 function get_chosen_category() {
689 if (window.location.hash === '#offense') {
691 } else if (window.location.hash === '#defense') {
693 } else if (window.location.hash === '#playing_time') {
694 return 'playing_time';
695 } else if (window.location.hash === '#per_point') {
702 function write_main_menu(chosen_category) {
704 if (chosen_category === 'general') {
705 let span = document.createElement('span');
706 span.innerText = 'General';
709 let a = document.createElement('a');
710 a.appendChild(document.createTextNode('General'));
711 a.setAttribute('href', '#general');
715 if (chosen_category === 'offense') {
716 let span = document.createElement('span');
717 span.innerText = 'Offense';
720 let a = document.createElement('a');
721 a.appendChild(document.createTextNode('Offense'));
722 a.setAttribute('href', '#offense');
726 if (chosen_category === 'defense') {
727 let span = document.createElement('span');
728 span.innerText = 'Defense';
731 let a = document.createElement('a');
732 a.appendChild(document.createTextNode('Defense'));
733 a.setAttribute('href', '#defense');
737 if (chosen_category === 'playing_time') {
738 let span = document.createElement('span');
739 span.innerText = 'Playing time';
742 let a = document.createElement('a');
743 a.appendChild(document.createTextNode('Playing time'));
744 a.setAttribute('href', '#playing_time');
748 if (chosen_category === 'per_point') {
749 let span = document.createElement('span');
750 span.innerText = 'Per point';
753 let a = document.createElement('a');
754 a.appendChild(document.createTextNode('Per point'));
755 a.setAttribute('href', '#per_point');
759 document.getElementById('mainmenu').replaceChildren(...elems);
762 // https://en.wikipedia.org/wiki/1.96#History
765 const ci_width = 100;
766 const ci_height = 20;
768 function make_binomial_ci(val, num, z) {
771 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
772 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
773 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
775 // Fix the signs so that we don't get -0.00.
776 low = Math.max(low, 0.0);
786 // These can only happen once per point, but you get -1 and +1
787 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
788 // and then we can rewrite back.
789 function make_efficiency_ci(points_won, points_completed, z)
791 let ci = make_binomial_ci(points_won, points_completed, z);
792 ci.val = 2.0 * ci.val - 1.0;
793 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
794 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
797 ci.desired = 0.0; // Desired = positive efficiency.
801 // Ds, throwaways and drops can happen multiple times per point,
802 // so they are Poisson distributed.
804 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
805 // since our rates are definitely below 2 per point).
806 function make_poisson_ci(val, num, z, inverted)
808 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
809 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
811 // Fix the signs so that we don't get -0.00.
812 low = Math.max(low, 0.0);
814 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
823 'inverted': inverted,
827 function make_table_general(players) {
830 let header = document.createElement('tr');
831 add_th(header, 'Player');
832 add_th(header, '+/-');
833 add_th(header, 'Soft +/-');
834 add_th(header, 'O efficiency');
835 add_th(header, 'D efficiency');
836 add_th(header, 'Points played');
840 for (const [q,p] of get_sorted_players(players)) {
841 if (q === 'globals') continue;
842 let row = document.createElement('tr');
843 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
844 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
845 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
846 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
847 let name = add_3cell(row, p.name, 'name'); // TODO: number?
848 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
849 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
850 add_3cell_ci(row, o_efficiency);
851 add_3cell_ci(row, d_efficiency);
852 add_3cell(row, p.points_played);
853 row.dataset.player = q;
858 let globals = players['globals'];
859 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
860 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
861 let row = document.createElement('tr');
865 add_3cell_ci(row, o_efficiency);
866 add_3cell_ci(row, d_efficiency);
867 add_3cell(row, globals.points_played);
873 function make_table_offense(players) {
876 let header = document.createElement('tr');
877 add_th(header, 'Player');
878 add_th(header, 'Goals');
879 add_th(header, 'Assists');
880 add_th(header, 'Hockey assists');
881 add_th(header, 'Throws');
882 add_th(header, 'Throwaways');
883 add_th(header, '%OK');
884 add_th(header, 'Catches');
885 add_th(header, 'Drops');
886 add_th(header, 'D-ed');
887 add_th(header, '%OK');
888 add_th(header, 'Stalls');
889 add_th(header, 'Soft +/-', 6);
900 for (const [q,p] of get_sorted_players(players)) {
901 if (q === 'globals') continue;
902 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
903 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
905 throw_ok.format = 'percentage';
906 catch_ok.format = 'percentage';
908 // Desire at least 90% percentage. Fairly arbitrary.
909 throw_ok.desired = 0.9;
910 catch_ok.desired = 0.9;
912 let row = document.createElement('tr');
913 add_3cell(row, p.name, 'name'); // TODO: number?
914 add_3cell(row, p.goals);
915 add_3cell(row, p.assists);
916 add_3cell(row, p.hockey_assists);
917 add_3cell(row, p.num_throws);
918 add_3cell(row, p.throwaways);
919 add_3cell_ci(row, throw_ok);
920 add_3cell(row, p.catches);
921 add_3cell(row, p.drops);
922 add_3cell(row, p.was_ds);
923 add_3cell_ci(row, catch_ok);
924 add_3cell(row, p.stallouts);
925 add_3cell(row, '+' + p.offensive_soft_plus);
926 add_3cell(row, '-' + p.offensive_soft_minus);
927 row.dataset.player = q;
931 num_throws += p.num_throws;
932 throwaways += p.throwaways;
933 catches += p.catches;
936 stallouts += p.stallouts;
940 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
941 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
942 throw_ok.format = 'percentage';
943 catch_ok.format = 'percentage';
944 throw_ok.desired = 0.9;
945 catch_ok.desired = 0.9;
947 let row = document.createElement('tr');
949 add_3cell(row, goals);
952 add_3cell(row, num_throws);
953 add_3cell(row, throwaways);
954 add_3cell_ci(row, throw_ok);
955 add_3cell(row, catches);
956 add_3cell(row, drops);
957 add_3cell(row, was_ds);
958 add_3cell_ci(row, catch_ok);
959 add_3cell(row, stallouts);
967 function make_table_defense(players) {
970 let header = document.createElement('tr');
971 add_th(header, 'Player');
972 add_th(header, 'Ds');
973 add_th(header, 'Pulls');
974 add_th(header, 'OOB pulls');
975 add_th(header, 'OOB%');
976 add_th(header, 'Avg. hang time (IB)');
977 add_th(header, 'Callahans');
978 add_th(header, 'Soft +/-', 6);
985 let sum_sum_time = 0;
988 for (const [q,p] of get_sorted_players(players)) {
989 if (q === 'globals') continue;
991 for (const t of p.pull_times) {
994 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
995 let oob_pct = 100 * p.oob_pulls / p.pulls;
997 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
998 ci_oob.format = 'percentage';
999 ci_oob.desired = 0.2; // Arbitrary.
1000 ci_oob.inverted = true;
1002 let row = document.createElement('tr');
1003 add_3cell(row, p.name, 'name'); // TODO: number?
1004 add_3cell(row, p.defenses);
1005 add_3cell(row, p.pulls);
1006 add_3cell(row, p.oob_pulls);
1007 add_3cell_ci(row, ci_oob);
1008 if (p.pulls > p.oob_pulls) {
1009 add_3cell(row, avg_time.toFixed(1) + ' sec');
1011 add_3cell(row, 'N/A');
1013 add_3cell(row, p.callahans);
1014 add_3cell(row, '+' + p.defensive_soft_plus);
1015 add_3cell(row, '-' + p.defensive_soft_minus);
1016 row.dataset.player = q;
1019 defenses += p.defenses;
1021 oob_pulls += p.oob_pulls;
1022 sum_sum_time += sum_time;
1023 callahans += p.callahans;
1027 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1028 ci_oob.format = 'percentage';
1029 ci_oob.desired = 0.2; // Arbitrary.
1030 ci_oob.inverted = true;
1032 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1033 let oob_pct = 100 * oob_pulls / pulls;
1035 let row = document.createElement('tr');
1037 add_3cell(row, defenses);
1038 add_3cell(row, pulls);
1039 add_3cell(row, oob_pulls);
1040 add_3cell_ci(row, ci_oob);
1041 if (pulls > oob_pulls) {
1042 add_3cell(row, avg_time.toFixed(1) + ' sec');
1044 add_3cell(row, 'N/A');
1046 add_3cell(row, callahans);
1054 function make_table_playing_time(players) {
1057 let header = document.createElement('tr');
1058 add_th(header, 'Player');
1059 add_th(header, 'Points played');
1060 add_th(header, 'Time played');
1061 add_th(header, 'O time');
1062 add_th(header, 'D time');
1063 add_th(header, 'Time on field');
1064 add_th(header, 'O points');
1065 add_th(header, 'D points');
1069 for (const [q,p] of get_sorted_players(players)) {
1070 if (q === 'globals') continue;
1071 let row = document.createElement('tr');
1072 add_3cell(row, p.name, 'name'); // TODO: number?
1073 add_3cell(row, p.points_played);
1074 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1075 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1076 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1077 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1078 add_3cell(row, p.offensive_points_completed);
1079 add_3cell(row, p.defensive_points_completed);
1080 row.dataset.player = q;
1085 let globals = players['globals'];
1086 let row = document.createElement('tr');
1088 add_3cell(row, globals.points_played);
1089 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1090 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1091 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1092 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1093 add_3cell(row, globals.offensive_points_completed);
1094 add_3cell(row, globals.defensive_points_completed);
1100 function make_table_per_point(players) {
1103 let header = document.createElement('tr');
1104 add_th(header, 'Player');
1105 add_th(header, 'Goals');
1106 add_th(header, 'Assists');
1107 add_th(header, 'Hockey assists');
1108 add_th(header, 'Ds');
1109 add_th(header, 'Throwaways');
1110 add_th(header, 'Recv. errors');
1111 add_th(header, 'Touches');
1117 let hockey_assists = 0;
1120 let receiver_errors = 0;
1122 for (const [q,p] of get_sorted_players(players)) {
1123 if (q === 'globals') continue;
1125 // Can only happen once per point, so these are binomials.
1126 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1127 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1128 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1129 // Arbitrarily desire at least 10% (not everybody can score or assist).
1130 ci_goals.desired = 0.1;
1131 ci_assists.desired = 0.1;
1132 ci_hockey_assists.desired = 0.1;
1134 let row = document.createElement('tr');
1135 add_3cell(row, p.name, 'name'); // TODO: number?
1136 add_3cell_ci(row, ci_goals);
1137 add_3cell_ci(row, ci_assists);
1138 add_3cell_ci(row, ci_hockey_assists);
1139 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1140 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1141 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1142 if (p.points_played > 0) {
1143 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1145 add_3cell(row, 'N/A');
1147 row.dataset.player = q;
1151 assists += p.assists;
1152 hockey_assists += p.hockey_assists;
1153 defenses += p.defenses;
1154 throwaways += p.throwaways;
1155 receiver_errors += p.drops + p.was_ds;
1156 touches += p.touches;
1160 let globals = players['globals'];
1161 let row = document.createElement('tr');
1163 if (globals.points_played > 0) {
1164 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1165 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1166 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1167 ci_goals.desired = 0.5;
1168 ci_assists.desired = 0.5;
1169 ci_hockey_assists.desired = 0.5;
1171 add_3cell_ci(row, ci_goals);
1172 add_3cell_ci(row, ci_assists);
1173 add_3cell_ci(row, ci_hockey_assists);
1175 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1176 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1177 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1179 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1181 add_3cell_with_filler_ci(row, 'N/A');
1182 add_3cell_with_filler_ci(row, 'N/A');
1183 add_3cell_with_filler_ci(row, 'N/A');
1184 add_3cell_with_filler_ci(row, 'N/A');
1185 add_3cell_with_filler_ci(row, 'N/A');
1186 add_3cell_with_filler_ci(row, 'N/A');
1187 add_3cell(row, 'N/A');
1194 function open_filter_menu(click_to_add_div) {
1195 document.getElementById('filter-submenu').style.display = 'none';
1196 let filter_div = click_to_add_div.parentElement;
1197 let filter_id = filter_div.dataset.filterId;
1199 let menu = document.getElementById('filter-add-menu');
1200 menu.parentElement.removeChild(menu);
1201 filter_div.appendChild(menu);
1202 menu.style.display = 'block';
1203 menu.replaceChildren();
1205 // Place the menu directly under the “click to add” label;
1206 // we don't anchor it since that label will move around
1207 // and the menu shouldn't.
1208 let rect = click_to_add_div.getBoundingClientRect();
1209 menu.style.left = rect.left + 'px';
1210 menu.style.top = (rect.bottom + 10) + 'px';
1212 let filterset = global_filters[filter_id];
1213 if (filterset === undefined) {
1214 global_filters[filter_id] = filterset = [];
1217 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1218 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1219 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1220 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1221 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1222 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1223 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1226 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1227 let item = document.createElement('div');
1228 item.classList.add('option');
1229 item.appendChild(document.createTextNode(title));
1231 let arrow = document.createElement('div');
1232 arrow.classList.add('arrow');
1233 arrow.textContent = '▸';
1234 item.appendChild(arrow);
1236 menu.appendChild(item);
1238 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1241 function find_all_ratios(json)
1245 for (const player of json['players']) {
1246 players[player['player_id']] = {
1247 'gender': player['gender'],
1248 'last_point_seen': null,
1251 for (const match of json['matches']) {
1252 for (const [q,p] of Object.entries(players)) {
1253 p.on_field_since = null;
1255 for (const e of match['events']) {
1256 let p = players[e['player']];
1257 let type = e['type'];
1258 if (type === 'in') {
1259 p.on_field_since = 1;
1260 } else if (type === 'out') {
1261 p.on_field_since = null;
1262 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1263 let code = find_gender_ratio_code(players);
1264 if (ratios[code] === undefined) {
1265 ratios[code] = code;
1266 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1267 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1268 match['description'] + ', ' + format_time(e['t']));
1277 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1278 let submenu = document.getElementById('filter-submenu');
1280 // Move to the same place as the top-level menu.
1281 submenu.parentElement.removeChild(submenu);
1282 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1285 const filter = find_filter(filterset, filter_type);
1288 if (filter_type === 'match') {
1289 for (const match of global_json['matches']) {
1291 'title': match['description'],
1292 'id': match['match_id']
1295 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1296 for (const player of global_json['players']) {
1298 'title': player['name'],
1299 'id': player['player_id']
1302 } else if (filter_type === 'formation_offense') {
1304 'title': '(None/unknown)',
1307 for (const formation of global_json['formations']) {
1308 if (formation['offense']) {
1310 'title': formation['name'],
1311 'id': formation['formation_id']
1315 } else if (filter_type === 'formation_defense') {
1317 'title': '(None/unknown)',
1320 for (const formation of global_json['formations']) {
1321 if (!formation['offense']) {
1323 'title': formation['name'],
1324 'id': formation['formation_id']
1328 } else if (filter_type === 'starting_on') {
1331 'id': false, // last_pull_was_ours
1335 'id': true, // last_pull_was_ours
1337 } else if (filter_type === 'gender_ratio') {
1338 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1346 for (const choice of choices) {
1347 let label = document.createElement('label');
1349 let subitem = document.createElement('div');
1350 subitem.classList.add('option');
1352 let check = document.createElement('input');
1353 check.setAttribute('type', 'checkbox');
1354 check.setAttribute('id', 'choice' + choice.id);
1355 if (filter !== null && filter.elements.has(choice.id)) {
1356 check.setAttribute('checked', 'checked');
1358 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id); });
1360 subitem.appendChild(check);
1361 subitem.appendChild(document.createTextNode(choice.title));
1363 label.appendChild(subitem);
1364 subitems.push(label);
1366 submenu.replaceChildren(...subitems);
1367 submenu.style.display = 'block';
1369 if (pill !== null) {
1370 let rect = pill.getBoundingClientRect();
1371 submenu.style.top = (rect.bottom + 10) + 'px';
1372 submenu.style.left = rect.left + 'px';
1374 // Position just outside the selected menu.
1375 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1376 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1377 submenu.style.left = (rect.right - 1) + 'px';
1381 // Find the right filter, if it exists.
1382 function find_filter(filterset, filter_type) {
1383 for (let f of filterset) {
1384 if (f.type === filter_type) {
1391 // Equivalent to Array.prototype.filter, but in-place.
1392 function inplace_filter(arr, cond) {
1394 for (let i = 0; i < arr.length; ++i) {
1402 function add_new_filterset() {
1403 let template = document.querySelector('.filter'); // First one is fine.
1404 let div = template.cloneNode(true);
1405 let add_menu = div.querySelector('#filter-add-menu');
1406 if (add_menu !== null) {
1407 div.removeChild(add_menu);
1409 let submenu = div.querySelector('#filter-submenu');
1410 if (submenu !== null) {
1411 div.removeChild(submenu);
1413 div.querySelector('.filters').replaceChildren();
1414 div.dataset.filterId = next_filterset_id++;
1415 template.parentElement.appendChild(div);
1418 function try_gc_filter_menus(cheap) {
1421 for (const filter_div of document.querySelectorAll('.filter')) {
1422 let id = filter_div.dataset.filterId;
1423 divs.push(filter_div);
1424 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1426 let last_div = divs[empties.length - 1];
1428 // See if we have two empty filter lists at the bottom of the list;
1429 // if so, we can remove one without it looking funny in the UI.
1430 // If not, we'll have to wait until closing the menu.
1431 // (The menu is positioned at the second-last one, so we can
1432 // remove the last one without issue.)
1433 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1434 delete global_filters[last_div.dataset.filterId];
1435 last_div.parentElement.removeChild(last_div);
1438 // This is a different situation from try_cheap_gc(), where we should
1439 // remove the one _not_ last. We might need to move the menu to the last one,
1440 // though, so it doesn't get lost.
1441 for (let i = 0; i < empties.length - 1; ++i) {
1446 delete global_filters[div.dataset.filterId];
1447 let add_menu = div.querySelector('#filter-add-menu');
1448 if (add_menu !== null) {
1449 div.removeChild(add_menu);
1450 last_div.appendChild(add_menu);
1452 let submenu = div.querySelector('#filter-submenu');
1453 if (submenu !== null) {
1454 div.removeChild(submenu);
1455 last_div.appendChild(submenu);
1457 div.parentElement.removeChild(div);
1462 function checkbox_changed(filter_div, filterset, e, filter_type, id) {
1463 let filter = find_filter(filterset, filter_type);
1464 let pills_div = filter_div.querySelector('.filters');
1465 if (e.target.checked) {
1466 // See if we must create a new empty filterset (since this went from
1467 // empty to non-empty).
1468 if (filterset.length === 0) {
1469 add_new_filterset();
1472 // See if we must add a new filter to the list.
1473 if (filter === null) {
1475 'type': filter_type,
1476 'elements': new Set([ id ]),
1478 filter.pill = make_filter_pill(filter_div, filterset, filter);
1479 filterset.push(filter);
1480 pills_div.appendChild(filter.pill);
1482 filter.elements.add(id);
1483 let new_pill = make_filter_pill(filter_div, filterset, filter);
1484 pills_div.replaceChild(new_pill, filter.pill);
1485 filter.pill = new_pill;
1488 filter.elements.delete(id);
1489 if (filter.elements.size === 0) {
1490 pills_div.removeChild(filter.pill);
1491 inplace_filter(filterset, f => f !== filter);
1493 if (filterset.length == 0) {
1494 try_gc_filter_menus(true);
1497 let new_pill = make_filter_pill(filter_div, filterset, filter);
1498 pills_div.replaceChild(new_pill, filter.pill);
1499 filter.pill = new_pill;
1503 process_matches(global_json, global_filters);
1506 function make_filter_pill(filter_div, filterset, filter) {
1507 let pill = document.createElement('div');
1508 pill.classList.add('filter-pill');
1510 if (filter.type === 'match') {
1514 for (const match_id of filter.elements) {
1515 all_names.push(find_match(match_id)['description']);
1517 let common_prefix = find_common_prefix_of_all(all_names);
1518 if (common_prefix !== null) {
1519 text += common_prefix + '(';
1523 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1524 for (const match_id of sorted_match_id) {
1528 let desc = find_match(match_id)['description'];
1529 if (common_prefix === null) {
1532 text += desc.substr(common_prefix.length);
1537 if (common_prefix !== null) {
1540 } else if (filter.type === 'player_any') {
1541 text = 'Player (any): ';
1542 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1544 for (const player_id of sorted_players) {
1548 text += find_player(player_id)['name'];
1551 } else if (filter.type === 'player_all') {
1553 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1555 for (const player_id of sorted_players) {
1559 text += find_player(player_id)['name'];
1562 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1563 const offense = (filter.type === 'formation_offense');
1571 for (const formation_id of filter.elements) {
1572 all_names.push(find_formation(formation_id)['name']);
1574 let common_prefix = find_common_prefix_of_all(all_names);
1575 if (common_prefix !== null) {
1576 text += common_prefix + '(';
1580 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1581 for (const formation_id of sorted_formation_id) {
1585 let desc = find_formation(formation_id)['name'];
1586 if (common_prefix === null) {
1589 text += desc.substr(common_prefix.length);
1594 if (common_prefix !== null) {
1597 } else if (filter.type === 'starting_on') {
1598 text = 'Starting on: ';
1600 if (filter.elements.has(false) && filter.elements.has(true)) {
1602 } else if (filter.elements.has(false)) {
1607 } else if (filter.type === 'gender_ratio') {
1611 for (const name of Array.from(filter.elements).sort()) {
1615 text += name; // FIXME
1620 let text_node = document.createElement('span');
1621 text_node.innerText = text;
1622 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
1623 pill.appendChild(text_node);
1625 pill.appendChild(document.createTextNode(' '));
1627 let delete_node = document.createElement('span');
1628 delete_node.innerText = '✖';
1629 delete_node.addEventListener('click', (e) => {
1630 // Delete this filter entirely.
1631 pill.parentElement.removeChild(pill);
1632 inplace_filter(filterset, f => f !== filter);
1633 if (filterset.length == 0) {
1634 try_gc_filter_menus(false);
1636 process_matches(global_json, global_filters);
1638 let add_menu = document.getElementById('filter-add-menu');
1639 let add_submenu = document.getElementById('filter-submenu');
1640 add_menu.style.display = 'none';
1641 add_submenu.style.display = 'none';
1643 pill.appendChild(delete_node);
1644 pill.style.cursor = 'pointer';
1649 function make_filter_marker(filterset) {
1651 for (const filter of filterset) {
1655 if (filter.type === 'match') {
1657 for (const match of global_json['matches']) {
1658 all_names.push(match['description']);
1660 let common_prefix = find_common_prefix_of_all(all_names);
1662 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1663 for (const match_id of sorted_match_id) {
1664 let desc = find_match(match_id)['description'];
1665 if (common_prefix === null) {
1666 text += desc.substr(0, 3);
1668 text += desc.substr(common_prefix.length, 3);
1671 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
1672 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1673 for (const player_id of sorted_players) {
1674 text += find_player(player_id)['name'].substr(0, 3);
1676 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1677 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1678 for (const formation_id of sorted_formation_id) {
1679 text += find_formation(formation_id)['name'].substr(0, 3);
1681 } else if (filter.type === 'starting_on') {
1682 if (filter.elements.has(false) && filter.elements.has(true)) {
1684 } else if (filter.elements.has(false)) {
1689 } else if (filter.type === 'gender_ratio') {
1691 for (const name of Array.from(filter.elements).sort()) {
1695 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
1703 function find_common_prefix(a, b) {
1705 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
1706 if (a[i] === b[i]) {
1715 function find_common_prefix_of_all(values) {
1716 if (values.length < 2) {
1719 let common_prefix = null;
1720 for (const desc of values) {
1721 if (common_prefix === null) {
1722 common_prefix = desc;
1724 common_prefix = find_common_prefix(common_prefix, desc);
1727 if (common_prefix.length >= 3) {
1728 return common_prefix;
1734 function find_match(match_id) {
1735 for (const match of global_json['matches']) {
1736 if (match['match_id'] === match_id) {
1743 function find_formation(formation_id) {
1744 for (const formation of global_json['formations']) {
1745 if (formation['formation_id'] === formation_id) {
1752 function find_player(player_id) {
1753 for (const player of global_json['players']) {
1754 if (player['player_id'] === player_id) {
1761 function player_pos(player_id) {
1763 for (const player of global_json['players']) {
1764 if (player['player_id'] === player_id) {
1772 function keep_match(match_id, filters) {
1773 for (const filter of filters) {
1774 if (filter.type === 'match') {
1775 return filter.elements.has(match_id);
1781 function find_gender_ratio_code(players) {
1783 for (const [q,p] of Object.entries(players)) {
1784 if (p.on_field_since === null) {
1787 let gender = p.gender;
1788 if (gender === '' || gender === undefined || gender === null) {
1791 if (map[gender] === undefined) {
1797 let all_genders = Array.from(Object.keys(map)).sort(
1799 if (map[a] !== map[b]) {
1800 return map[b] - map[a]; // Reverse numeric.
1810 for (const g of all_genders) {
1821 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
1822 if (filter.type === 'player_any') {
1823 for (const p of Array.from(filter.elements)) {
1824 if (players[p].on_field_since !== null) {
1829 } else if (filter.type === 'player_all') {
1830 for (const p of Array.from(filter.elements)) {
1831 if (players[p].on_field_since === null) {
1836 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1837 for (const f of Array.from(filter.elements)) {
1838 if (formations_used_this_point.has(f)) {
1843 } else if (filter.type === 'starting_on') {
1844 return filter.elements.has(last_pull_was_ours);
1845 } else if (filter.type === 'gender_ratio') {
1846 return filter.elements.has(find_gender_ratio_code(players));
1851 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
1852 for (const filter of filters) {
1853 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
1860 // Heuristic: If we go at least ten seconds without the possession changing
1861 // or the operator specifying some other formation, we probably play the
1862 // same formation as the last point.
1863 function should_reuse_last_formation(events, t) {
1864 for (const e of events) {
1868 if (e.t > t + 10000) {
1871 const type = e.type;
1872 if (type === 'their_goal' || type === 'goal' ||
1873 type === 'set_defense' || type === 'set_offense' ||
1874 type === 'throwaway' || type === 'their_throwaway' ||
1875 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
1876 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
1877 type === 'formation_offense' || type === 'formation_defense') {
1884 function possibly_close_menu(e) {
1885 if (e.target.closest('.filter-click-to-add') === null &&
1886 e.target.closest('#filter-add-menu') === null &&
1887 e.target.closest('#filter-submenu') === null &&
1888 e.target.closest('.filter-pill') === null) {
1889 let add_menu = document.getElementById('filter-add-menu');
1890 let add_submenu = document.getElementById('filter-submenu');
1891 add_menu.style.display = 'none';
1892 add_submenu.style.display = 'none';
1893 try_gc_filter_menus(false);
1897 let global_sort = {};
1899 function sort_by(th) {
1900 let tr = th.parentElement;
1902 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
1903 let element = tr.children[column_idx];
1904 if (element === th) {
1905 ++child_idx; // Pad.
1908 if (element.hasAttribute('colspan')) {
1909 child_idx += parseInt(element.getAttribute('colspan'));
1916 let table = tr.parentElement;
1917 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
1918 let row = table.children[row_idx];
1919 let player = parseInt(row.dataset.player);
1920 let value = row.children[child_idx].textContent;
1921 global_sort[player] = value;
1925 function get_sorted_players(players)
1927 let p = Object.entries(players);
1928 if (global_sort.length !== 0) {
1930 let ai = parseFloat(global_sort[a[0]]);
1931 let bi = parseFloat(global_sort[b[0]]);
1932 if (ai == ai && bi == bi) {
1933 return bi - ai; // Reverse numeric.
1934 } else if (global_sort[a[0]] < global_sort[b[0]]) {
1936 } else if (global_sort[a[0]] > global_sort[b[0]]) {