neslinesli93 / PoliTO media

// ==UserScript==
// @name			PoliTO media
// @author			neslinesli93
// @namespace		https://didattica.polito.it/portal/page/portal/home/Studente
// @version			0.2
// @require			https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// @include			https://*.*
// @grant			unsafeWindow
// ==/UserScript==

$(window).load(function () {    
    var tables, marks_table, marks_array, len_marks, weighted_marks, not_weighted_marks, current_mark, current_credits, weighted_avg, not_weighted_avg, total_credits, skipped_credits, skipped_marks;
    
    tables = $("table.RegionBorderMao>tbody>tr>td>table");
    marks_table = tables[tables.length - 5].children[0];
    marks_array = marks_table.children;
    len_marks = marks_array.length;

    weighted_marks = 0;
    not_weighted_marks = 0;
    skipped_marks = 0;
    skipped_credits = 0;
    for (var i = 1; i < len_marks - 1; i++)
    {
        current_credits = parseInt(marks_array[i].children[1].innerHTML);
        current_mark = marks_array[i].children[2].innerHTML;
        
        // Really I don't know if this is different for non-italian students
        if (isNaN(current_mark)) {
            if (current_mark === "30 e lode") {
                current_mark = 31;
            } else {
                // Probably a mark that is not used for computing the average (IELTS, ecc)
                skipped_credits += current_credits;
                skipped_marks += 1;
                continue;
            } 
        } else {
            current_mark = parseInt(current_mark);
        }
        
        not_weighted_marks += current_mark;
        weighted_marks += current_mark * current_credits;
    }
    
    total_credits = parseInt(marks_array[len_marks - 1].children[1].children[0].innerHTML);
    console.log("Total credits: ", total_credits);
    console.log("Meaningful credits: ", total_credits - skipped_credits);
    console.log("NWM: ", not_weighted_marks)
    console.log("WM: ", weighted_marks);
    console.log("Total subjects: ", len_marks - 1 - 1);
    console.log("Meaningful subjects: ", len_marks - 1 - 1 - skipped_marks);
    
    not_weighted_avg = (not_weighted_marks / (len_marks - 1 - 1 - skipped_marks)).toFixed(2); // Same in the for statement, which starts from 1 and ends at len_marks-1
    weighted_avg = (weighted_marks / (total_credits - skipped_credits)).toFixed(2);
    
    var tr_non_weigh = "<tr><td class='policorpo' align='right'><b>Media non pesata:</b></td><td class='policorpo' align='center'><b>"+not_weighted_avg+"</b></td><td align='center' colspan='2'>&nbsp;</td></tr>",
        tr_weigh = "<tr><td class='policorpo' align='right'><b>Media pesata:</b></td><td class='policorpo' align='center'><b>"+weighted_avg+"</b></td><td align='center' colspan='2'>&nbsp;</td></tr>";

    $(marks_table).append(tr_non_weigh);
    $(marks_table).append(tr_weigh);
});