-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.js
76 lines (59 loc) · 2.35 KB
/
utils.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
const nodeHtmlToImage = require('node-html-to-image');
const K_FACTOR = 32; // You can adjust the K-factor to control the impact of a single match on the Elo score
function calculateExpectedScore(ratingA, ratingB) {
return 1 / (1 + Math.pow(10, (ratingB - ratingA) / 400));
}
const calculateUpdatedElo = (eloA, eloB, actualScoreA, actualScoreB) => {
const expectedScoreA = calculateExpectedScore(eloA, eloB);
const expectedScoreB = calculateExpectedScore(eloB, eloA);
const newEloA = eloA + K_FACTOR * (actualScoreA - expectedScoreA);
const newEloB = eloB + K_FACTOR * (actualScoreB - expectedScoreB);
return [newEloA.toFixed(2), newEloB.toFixed(2)].map(parseFloat);
};
exports.updateElo = async (target1, target2, winnerId) => {
const actualScore1 = String(winnerId) === String(target1.id) ? 1 : 0;
const actualScore2 = 1 - actualScore1;
const [newElo1, newElo2] = calculateUpdatedElo(target1['elo'], target2['elo'], actualScore1, actualScore2);
await target1.update({ elo: newElo1 });
await target2.update({ elo: newElo2 });
}
exports.decayElo = (participant, lastActiveDate, currentDate, customDecaySettings = null ) => {
const defaultDecaySettings = [
{ threshold: 10, decayPerDay: 1, minElo: 0, maxElo: 1200 },
{ threshold: 7, decayPerDay: 3, minElo: 1201, maxElo: 1800 },
{ threshold: 3, decayPerDay: 5, minElo: 1801, maxElo: Infinity },
];
const decaySettings = customDecaySettings || defaultDecaySettings;
const daysInactive = Math.floor((currentDate - lastActiveDate) / (1000 * 3600 * 24));
let participantElo = parseFloat(participant.elo) || 0;
for (let day = 1; day <= daysInactive; day++) {
const tier = decaySettings.find(
t => participantElo >= t.minElo && participantElo <= t.maxElo
);
if (!tier) break;
if (day > tier.threshold) {
participantElo -= tier.decayPerDay;
if (participantElo < 0) {
participantElo = 0;
break;
}
}
}
participant.elo = participantElo.toFixed(2);
return participant;
};
exports.generateBracketImage = async (bracketHtml) => {
try {
const image = await nodeHtmlToImage({
html: bracketHtml
});
return image;
} catch (err) {
console.error(err);
return false;
}
};
exports.isPowerOfTwo = n => {
// Check if the number is non-negative and has only one set bit
return n > 0 && (n & (n - 1)) === 0;
};