-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrym-track-rating-calculator.js
56 lines (47 loc) · 1.8 KB
/
rym-track-rating-calculator.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
// Save buttons locations
const trackRatingBtn = document.querySelector('#track_rating_btn');
const trackRatingsSave = document.querySelector('#track_ratings_save_btn');
// Find track ratings and songs
const elements = document.querySelectorAll('[id^="rating_num_z_"]');
const duration = document.querySelector('.section_tracklisting').querySelectorAll('span.tracklist_duration');
// Get final score
const calculateScore = (ratings, seconds) => {
const totalSeconds = seconds.reduce((x, y) => Number(x) + Number(y), 0);
let totalScore = 0;
// Verify if there is at least one song rated
if (ratings.length && seconds.length && ratings.length === seconds.length) {
for (let i = 0; i < seconds.length; i++) {
totalScore += Number(ratings[i]) * 2 * Number(seconds[i]);
}
return totalScore / totalSeconds;
}
return null;
}
function score() {
const ratings = [];
const seconds = [];
// Save songs and ratings
elements.forEach(element => ratings.push(element.textContent.trim()));
duration.forEach(({ dataset: { inseconds } }) => {
if (inseconds > 0) {
seconds.push(inseconds);
}
});
// Delete non rated songs
for (let i = 0; i < seconds.length; i++) {
if (ratings[i] === '---') {
seconds.splice(i, 1);
ratings.splice(i, 1);
i--;
}
}
// Calculate the score and update the button
const finalScore = calculateScore(ratings, seconds);
if (finalScore !== null) {
trackRatingBtn.textContent = `Track ratings [${finalScore.toFixed(2)}]`;
} else {
trackRatingBtn.textContent = 'Track ratings';
}
}
trackRatingBtn.addEventListener('click',score);
trackRatingsSave.addEventListener('click',score);