-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathattempt-result.js
More file actions
585 lines (530 loc) · 18.4 KB
/
Copy pathattempt-result.js
File metadata and controls
585 lines (530 loc) · 18.4 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
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import { times } from "./utils";
import { shouldComputeAverage } from "./result";
export const SKIPPED_VALUE = 0;
export const DNF_VALUE = -1;
export const DNS_VALUE = -2;
export function isComplete(attemptResult) {
return attemptResult > 0;
}
export function isSkipped(attemptResult) {
return attemptResult === SKIPPED_VALUE;
}
export function toMonotonic(attemptResult) {
return isComplete(attemptResult) ? attemptResult : Infinity;
}
export function compareAttemptResults(attemptResult1, attemptResult2) {
if (!isComplete(attemptResult1) && !isComplete(attemptResult2)) return 0;
if (!isComplete(attemptResult1) && isComplete(attemptResult2)) return 1;
if (isComplete(attemptResult1) && !isComplete(attemptResult2)) return -1;
return attemptResult1 - attemptResult2;
}
/**
* Returns the specified number of attempt results filling missing ones with 0.
*/
export function padSkipped(attemptResults, numberOfAttempts) {
return times(numberOfAttempts, (index) =>
index < attemptResults.length ? attemptResults[index] : SKIPPED_VALUE,
);
}
/**
* Removes trailing skipped attempt results from the given list.
*/
export function trimTrailingSkipped(attemptResults) {
if (attemptResults.length === 0) return [];
if (attemptResults[attemptResults.length - 1] === SKIPPED_VALUE) {
return trimTrailingSkipped(attemptResults.slice(0, -1));
}
return attemptResults;
}
/**
* Returns the best attempt result from the given list.
*
* @example
* best([900, -1, 700]); // => 700
*/
export function best(attemptResults) {
const nonSkipped = attemptResults.filter((attempt) => !isSkipped(attempt));
const completeAttempts = attemptResults.filter(isComplete);
if (nonSkipped.length === 0) return SKIPPED_VALUE;
if (completeAttempts.length === 0) return Math.max(...nonSkipped);
return Math.min(...completeAttempts);
}
/**
* Returns the average of the given attempt results.
*
* Calculates either Mean of 3 or Average of 5 depending on
* the number of the given attempt results.
*
* @example
* average([900, -1, 700, 800, 900], '333'); // => 800
* average([900, -1, 700, 800, -1], '333'); // => -1
*/
export function average(attemptResults, eventId) {
if (!eventId) {
/* If eventId is omitted, the average is still calculated correctly except for FMC
and that may be a hard to spot bug, so better enforce explicity here. */
throw new Error("Missing argument: eventId");
}
if (eventId === "333mbf") return SKIPPED_VALUE;
if (attemptResults.some(isSkipped)) return SKIPPED_VALUE;
if (eventId === "333fm") {
const scaled = attemptResults.map((attemptResult) => attemptResult * 100);
switch (attemptResults.length) {
case 3:
return meanOfX(scaled);
case 5:
return averageOf5(scaled);
default:
throw new Error(
`Invalid number of attempt results, expected 3 or 5, got ${attemptResults.length}.`,
);
}
}
switch (attemptResults.length) {
case 3:
return roundOver10Mins(meanOfX(attemptResults));
case 5:
return roundOver10Mins(averageOf5(attemptResults));
default:
throw new Error(
`Invalid number of attempt results, expected 3 or 5, got ${attemptResults.length}.`,
);
}
}
/* See: https://www.worldcubeassociation.org/regulations/#9f2 */
function roundOver10Mins(value) {
if (!isComplete(value)) return value;
if (value <= 10 * 6000) return value;
return Math.round(value / 100) * 100;
}
/* See: https://www.worldcubeassociation.org/regulations/#9f2 */
function truncateOver10Mins(value) {
if (!isComplete(value)) return value;
if (value <= 10 * 6000) return value;
return Math.floor(value / 100) * 100;
}
function averageOf5(attemptResults) {
const [, x, y, z] = attemptResults.slice().sort(compareAttemptResults);
return meanOfX([x, y, z]);
}
function meanOfX(attemptResults) {
if (!attemptResults.every(isComplete)) return DNF_VALUE;
return mean(attemptResults);
}
function mean(values) {
const sum = values.reduce((x, y) => x + y, 0);
return Math.round(sum / values.length);
}
/**
* Returns projected average.
*
* Note that contrarily to other functions in this module, this
* function expects a non-padded and incomplete list of attempt
* results (without trailing skipped values).
*
* Projections are defined as follows:
*
* - mo3 events: mean of current solves
* - ao5 events:
* - 1-2 solves: mean of current solves
* - 3-4 solves: median of current solves
*
* When all result attempts are present, the return value is the same
* as the usual average.
*/
export function projectedAverage(attemptResults, eventId, format) {
if (attemptResults.length === 0) return SKIPPED_VALUE;
if (eventId === "333fm") {
if (!attemptResults.every(isComplete)) return DNF_VALUE;
const scaled = attemptResults.map((attemptResult) => attemptResult * 100);
return mean(scaled);
}
if (format.numberOfAttempts === 3) {
return meanOfX(attemptResults);
}
if (format.numberOfAttempts === 5) {
if (attemptResults.length < 3) {
return meanOfX(attemptResults);
}
if (attemptResults.length === 3) {
const [, x] = attemptResults.slice().sort(compareAttemptResults);
return x;
}
if (attemptResults.length === 4) {
const [, x, y] = attemptResults.slice().sort(compareAttemptResults);
return meanOfX([x, y]);
}
return averageOf5(attemptResults);
}
throw new Error("Unexpected format");
}
/**
* Calculates the best possible average of 5 for the given attempts.
*
* Expects exactly 4 attempt results to be given.
*
* @example
* bestPossibleAverage([3642, 3102, 3001, 2992]); // => 3032
* bestPossibleAverage([6111, -1, -1, 6000]); // => -1
* bestPossibleAverage([4822, 4523, 4233, -1]; // => 4526
*/
export function bestPossibleAverage(attemptResults) {
if (attemptResults.length !== 4) {
throw new Error(
`Invalid number of attempt results, expected 4, got ${attemptResults.length}.`,
);
}
const [x, y, z] = attemptResults.slice().sort(compareAttemptResults);
const mean = meanOfX([x, y, z]);
return roundOver10Mins(mean);
}
/**
* Calculates the worst possible average of 5 for the given attempts.
*
* Expects exactly 4 attempt results to be given.
*
* @example
* worstPossibleAverage([3642, 3102, 3001, 2992]); // => 3248
* worstPossibleAverage([6111, -1, -1, 6000]); // => -1
* worstPossibleAverage([6111, -1, 6000, 5999]); // => -1
*/
export function worstPossibleAverage(attemptResults) {
if (attemptResults.length !== 4) {
throw new Error(
`Invalid number of attempt results, expected 4, got ${attemptResults.length}.`,
);
}
const [, x, y, z] = attemptResults.slice().sort(compareAttemptResults);
const mean = meanOfX([x, y, z]);
return roundOver10Mins(mean);
}
/**
* Returns an object representation of the given MBLD attempt result.
*
* @example
* decodeMbldAttemptResult(900348002); // => { solved: 11, attempted: 13, centiseconds: 348000 }
*/
export function decodeMbldAttemptResult(value) {
if (value <= 0) return { solved: 0, attempted: 0, centiseconds: value };
const missed = value % 100;
const seconds = Math.floor(value / 100) % 1e5;
const points = 99 - (Math.floor(value / 1e7) % 100);
const solved = points + missed;
const attempted = solved + missed;
const centiseconds = seconds === 99999 ? null : seconds * 100;
return { solved, attempted, centiseconds };
}
/**
* Returns a MBLD attempt result based on the given object representation.
*
* @example
* encodeMbldAttemptResult({ solved: 11, attempted: 13, centiseconds: 348000 }); // => 900348002
*/
export function encodeMbldAttemptResult({ solved, attempted, centiseconds }) {
if (centiseconds <= 0) return centiseconds;
const missed = attempted - solved;
const points = solved - missed;
const seconds = Math.floor(
(centiseconds || 9999900) / 100,
); /* 99999 seconds is used for unknown time. */
return (99 - points) * 1e7 + seconds * 1e2 + missed;
}
/**
* Returns the number of points for the given MBLD attempt result.
*/
export function mbldAttemptResultToPoints(attemptResult) {
const { solved, attempted } = decodeMbldAttemptResult(attemptResult);
const missed = attempted - solved;
return solved - missed;
}
/**
* Converts centiseconds to a human-friendly string.
*/
export function centisecondsToClockFormat(centiseconds) {
if (!Number.isFinite(centiseconds)) {
throw new Error(
`Invalid centiseconds, expected positive number, got ${centiseconds}.`,
);
}
return new Date(centiseconds * 10)
.toISOString()
.substr(11, 11)
.replace(/^[0:]*(?!\.)/g, "");
}
/**
* Converts the given attempt result to a human-friendly string.
*
* @example
* formatAttemptResult(-1, '333'); // => 'DNF'
* formatAttemptResult(6111, '333'); // => '1:01.11'
* formatAttemptResult(900348002, '333mbf'); // => '11/13 58:00'
*/
export function formatAttemptResult(attemptResult, eventId) {
if (attemptResult === SKIPPED_VALUE) return "";
if (attemptResult === DNF_VALUE) return "DNF";
if (attemptResult === DNS_VALUE) return "DNS";
if (eventId === "333mbf") return formatMbldAttemptResult(attemptResult);
if (eventId === "333fm") return formatFmAttemptResult(attemptResult);
return centisecondsToClockFormat(attemptResult);
}
function formatMbldAttemptResult(attemptResult) {
const { solved, attempted, centiseconds } =
decodeMbldAttemptResult(attemptResult);
const clockFormat = centisecondsToClockFormat(centiseconds);
const shortClockFormat = clockFormat.replace(/\.00$/, "");
return `${solved}/${attempted} ${
centiseconds < 6000 ? `0:${shortClockFormat}` : shortClockFormat
}`;
}
function formatFmAttemptResult(attemptResult) {
/* Note: FM singles are stored as the number of moves (e.g. 25),
while averages are stored with 2 decimal places (e.g. 2533 for an average of 25.33 moves). */
const isAverage = attemptResult >= 1000;
return isAverage
? (attemptResult / 100).toFixed(2)
: attemptResult.toString();
}
/**
* Alters the given MBLD decoded value, so that it conforms to the WCA regulations.
*/
export function autocompleteMbldDecodedValue({
attempted,
solved,
centiseconds,
}) {
// We expect the values to be entered left-to-right, so we reset to
// defaults otherwise
if ((!solved && attempted) || (!solved && !attempted && centiseconds > 0)) {
return { solved: 0, attempted: 0, centiseconds: 0 };
}
if (!attempted || solved > attempted) {
return { solved, attempted: solved, centiseconds };
}
// See https://www.worldcubeassociation.org/regulations/#9f12c
if (solved < attempted / 2 || solved <= 1) {
return { solved: 0, attempted: 0, centiseconds: DNF_VALUE };
}
// See https://www.worldcubeassociation.org/regulations/#H1b
// But allow additional two +2s per cube over the limit, just in case.
if (
centiseconds >
10 * 60 * 100 * Math.min(6, attempted) + attempted * 2 * 2 * 100
) {
return { solved: 0, attempted: 0, centiseconds: DNF_VALUE };
}
return { solved, attempted, centiseconds };
}
/**
* Alters the given FM attempt result, so that it conforms to the WCA regulations.
*/
export function autocompleteFmAttemptResult(moves) {
// See https://www.worldcubeassociation.org/regulations/#E2d1
if (moves > 80) return DNF_VALUE;
return moves;
}
/**
* Alters the given time attempt result, so that it conforms to the WCA regulations.
*/
export function autocompleteTimeAttemptResult(time) {
// See https://www.worldcubeassociation.org/regulations/#9f2
return truncateOver10Mins(time);
}
/**
* Checks whether a given attempt is a world record of the given type.
* Returns the corresponding boolean.
*/
export function isWorldRecord(
attemptResult,
eventId,
type,
officialWorldRecords = [],
) {
const wr =
officialWorldRecords.find(
(wr) => wr.type === type && wr.event.id === eventId,
) || null;
return (
wr !== null &&
isComplete(attemptResult) &&
attemptResult <= wr.attemptResult
);
}
/**
* Checks the given attempt results for discrepancies and returns
* a warning message if some are found.
*/
export function attemptResultsWarning(
attemptResults,
eventId,
officialWorldRecords = [],
results = [],
) {
const skippedGapIndex =
trimTrailingSkipped(attemptResults).indexOf(SKIPPED_VALUE);
if (skippedGapIndex !== -1) {
return {
description: `You've omitted attempt ${
skippedGapIndex + 1
}. Make sure it's intentional.`,
};
}
const completeAttempts = attemptResults.filter(isComplete);
if (completeAttempts.length > 0) {
const bestSingle = Math.min(...completeAttempts);
const newWorldRecordSingle = isWorldRecord(
bestSingle,
eventId,
"single",
officialWorldRecords,
);
if (newWorldRecordSingle) {
return {
description: `The result you're trying to submit includes a new world record single
(${formatAttemptResult(bestSingle, eventId)}).
Please check that you are entering results for the right event and that all
the entered attempts are accurate. Type "world record" below to confirm that
you are confident that it is indeed a world record result.`,
confirmationKeyword: "world record",
};
}
if (shouldComputeAverage(eventId, attemptResults.length)) {
const newWorldRecordAverage = isWorldRecord(
average(attemptResults, eventId),
eventId,
"average",
officialWorldRecords,
);
if (newWorldRecordAverage) {
return {
description: `The result you're trying to submit is a new world record average
(${formatAttemptResult(average(attemptResults, eventId), eventId)}).
Please check that you are entering results for the right event and that all
the entered attempts are accurate. Type "world record" below to confirm that
you are confident that it is indeed a world record result.`,
confirmationKeyword: "world record",
};
}
}
if (checkForDnsFollowedByValidResult(attemptResults)) {
return {
description: `There's at least one DNS followed by a valid result. Please ensure it is indeed a DNS and not a DNF.`,
};
}
if (eventId === "333mbf") {
const lowTimeIndex = attemptResults.findIndex((attempt) => {
const { attempted, centiseconds } = decodeMbldAttemptResult(attempt);
return attempt > 0 && centiseconds / attempted < 30 * 100;
});
if (lowTimeIndex !== -1) {
return {
description: `The result you're trying to submit seems to be impossible:
attempt ${lowTimeIndex + 1} is done in
less than 30 seconds per cube tried.
If you want to enter minutes, don't forget to add two zeros
for centiseconds at the end of the score.`,
};
}
} else {
const worstSingle = Math.max(...completeAttempts);
const inconsistent = worstSingle > bestSingle * 4;
if (inconsistent) {
return {
description: `The result you're trying to submit seem to be inconsistent.
There's a big difference between the best single
(${formatAttemptResult(bestSingle, eventId)}) and the worst single
(${formatAttemptResult(worstSingle, eventId)}).
Please check that the results are accurate.`,
};
}
}
// Check whether this result is a duplicate of existing results in the same round.
// Excludes FMC and all-DNF results since ties are common.
if (eventId !== "333fm" && completeAttempts.length > 0) {
const matches = findAllMatchingResults(attemptResults, results);
if (matches.length > 0) {
const matchesString = matches
.map((match) => `${match.person.name} (${match.person.id})`)
.join(", ");
return {
description: `The result you're trying to submit matches all results for
the following competitor${matches.length > 1 ? "s" : ""}: ${matchesString}.
Please check that the results are accurate.`,
};
}
}
}
return null;
}
/**
* Alters the given attempt results, so that they conform to the given time limit.
*/
export function applyTimeLimit(attemptResults, timeLimit) {
if (timeLimit === null) return attemptResults;
if (timeLimit.cumulativeRoundWcifIds.length === 0) {
return attemptResults.map((attemptResult) =>
attemptResult >= timeLimit.centiseconds ? DNF_VALUE : attemptResult,
);
} else {
// Note: for now cross-round cumulative time limits are handled
// as single-round cumulative time limits for each of the rounds.
const [updatedAttemptResults] = attemptResults.reduce(
([updatedAttemptResults, sum], attemptResult) => {
const updatedSum = attemptResult > 0 ? sum + attemptResult : sum;
const updatedAttemptResult =
attemptResult > 0 && updatedSum >= timeLimit.centiseconds
? DNF_VALUE
: attemptResult;
return [updatedAttemptResults.concat(updatedAttemptResult), updatedSum];
},
[[], 0],
);
return updatedAttemptResults;
}
}
/**
* Alters the given attempt results, so that they conform to the given cutoff.
*/
export function applyCutoff(attemptResults, cutoff) {
if (meetsCutoff(attemptResults, cutoff)) {
return attemptResults;
}
return attemptResults.map((attemptResult, index) =>
index < cutoff.numberOfAttempts ? attemptResult : SKIPPED_VALUE,
);
}
/**
* Checks if the given attempt results meet the given cutoff.
*/
export function meetsCutoff(attemptResults, cutoff) {
if (!cutoff) return true;
const { numberOfAttempts, attemptResult } = cutoff;
return attemptResults
.slice(0, numberOfAttempts)
.some((attempt) => attempt > 0 && attempt < attemptResult);
}
function checkForDnsFollowedByValidResult(attemptResults) {
const dnsIndex = attemptResults.findIndex((attempt) => attempt === DNS_VALUE);
if (dnsIndex === -1) return false;
return attemptResults.some(
(attempt, index) =>
index > dnsIndex && attempt !== SKIPPED_VALUE && attempt !== DNS_VALUE,
);
}
/**
* Check whether an attempt matches an existing attempt exactly.
*/
function findAllMatchingResults(attemptResults, results) {
const filteredAttemptResults = trimTrailingSkipped(attemptResults);
const matches = results.filter((result) => {
if (result.attempts.length !== filteredAttemptResults.length) {
return false;
}
for (let i = 0; i < result.attempts.length; i++) {
if (result.attempts[i].result !== filteredAttemptResults[i]) {
return false;
}
}
return true;
});
return matches;
}