alchzh / Add Interrupts per 20 Tossups Heard to NAQT

// ==UserScript==
// @name          Add Interrupts per 20 Tossups Heard to NAQT
// @description   Adds a sortable "Interrupts per 20 Tossups Heard" column to all compatible NAQT stats tables
// @include       https://www.naqt.com/*
// grant          none
// @namespace     https://openuserjs.org/users/alchzh
// @copyright     2021, alchzh (https://openuserjs.org/users/alchzh)
// @version       0.1
// @author        alchzh
// @licence       MIT
// ==/UserScript==

/* global $ */

function formatNumber(n) {
  if (Number.isNaN(n)) {
    return "n/a";
  }
  return Number(Math.round(n + 'e2') + 'e-2').toFixed(2);
}

$("th[title='Tossups heard'] ~ th[title='Interrupts'] ~ th[title='Points per 20 tossups heard']:last-child").each(function() {
  var PP20TUH = $(this);

  PP20TUH.before("<th class='numeric' title='Interrupts per 20 tossups heard'>IP20TUH</th>");

  var TUH_idx = PP20TUH.siblings("th[title='Tossups heard']").index();
  var TUH_last_idx = PP20TUH.index() - TUH_idx;
  var I_idx = PP20TUH.siblings("th[title='Interrupts']").index() - TUH_idx;
  

  PP20TUH.closest("table").find("tbody > tr > td:nth-last-child(" + TUH_last_idx + ")").each(function() {
    var tr = $(this).parent();
    var IP20TUH;
    if ($(this).text() === "0") {
      IP20TUH = 0;
    } else {
      IP20TUH = formatNumber(parseInt(tr.children().eq(-TUH_last_idx + I_idx).text(), 10) * 20 / parseInt($(this).text(), 10));
    }
    tr.children().last().before("<td class='numeric'>" + IP20TUH + "</td>")
  });
})