aboutsummaryrefslogtreecommitdiff
path: root/parts/end.html
blob: cc5102725303aaf7b88842abec496d243b46387e (plain)
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
      </tbody>
    </table>
  </div>
</body>

<script type="text/javascript">
  const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
  prevColumnSorted = document.getElementsByClassName("current-sort")[0];
  
  const comparer = (idx, asc) => (a, b) => ((v1, v2) => 
    v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
    )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
  
  function doSort(th) {
    console.log("Doing sort to: ", th.textContent, th);
    
    const table = th.closest('table');
    const tbody = table.querySelector('tbody');
    const columnIndex = Array.from(th.parentNode.children).indexOf(th);
    
    // Toggle sort direction
    if (prevColumnSorted == th) {
      this.asc = !this.asc;
    } else {
      this.asc = true;
    }
    
    // Get all rows, sort them, then reappend to tbody
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const sortedRows = rows.sort(comparer(columnIndex, this.asc));
    
    sortedRows.forEach(row => tbody.appendChild(row));
    prevColumnSorted = th;
  }
  
  // Event listeners and initial sort
  document.querySelectorAll('th').forEach(th => th.addEventListener('click', () => {
    document.getElementsByClassName("current-sort")[0].classList.remove("current-sort");
    th.classList.add("current-sort");
    doSort(th);
  }));
  
  doSort(document.getElementsByClassName("current-sort")[0]);
</script>

</html>