Jstris table sort

add sorting to tables

目前為 2023-09-10 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Jstris table sort
  3. // @namespace
  4. // @version 0.2
  5. // @description add sorting to tables
  6. // @author mxmossy
  7. // @match https://*.jstris.jezevec10.com/*
  8. // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
  9. // @grant none
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. // adapted from https://stackoverflow.com/questions/14267781/sorting-html-table-with-javascript
  15. var getCellValue = function(tr, idx){ return tr.children[idx].innerText || tr.children[idx].textContent; }
  16.  
  17. var format = function(s){return s.replace(/[:\- ]/g, "")}
  18.  
  19. var comparer = function(idx, asc) {
  20. return function(a, b) {
  21. return function(v1, v2) {
  22. if(v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2)){
  23. return v1 - v2;
  24. }
  25. else if(v1.includes(":") || v2.includes(":")){
  26. return parseFloat(format(v1)) - parseFloat(format(v2));
  27. }
  28. else return v1.toString().localeCompare(format(v2));
  29. }(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
  30. }};
  31.  
  32. // do the work...
  33. Array.prototype.slice.call(document.querySelectorAll('th')).forEach(function(th) { th.addEventListener('click', function() {
  34. var table = th.parentNode;
  35. while(table.tagName.toUpperCase() != 'TABLE') table = table.parentNode;
  36. var tableBody = table.querySelector('tbody');
  37. Array.prototype.slice.call(table.querySelectorAll('tbody tr:nth-child(n+1)'))
  38. .sort(comparer(Array.prototype.slice.call(th.parentNode.children).indexOf(th), this.asc = !this.asc))
  39. .forEach(function(tr) { tableBody.appendChild(tr) });
  40. })});
  41.  
  42. })();