HummingBirdAnimeClient/frontEndSrc/js/base/sort-tables.js

83 lines
2.0 KiB
JavaScript
Raw Normal View History

2018-08-10 20:09:28 -04:00
const LightTableSorter = (() => {
let th = null;
let cellIndex = null;
let order = '';
const text = (row) => row.cells.item(cellIndex).textContent.toLowerCase();
2018-08-10 20:09:28 -04:00
const sort = (a, b) => {
let textA = text(a);
let textB = text(b);
2022-01-02 17:48:20 -05:00
console.log("Comparing " + textA + " and " + textB)
2022-01-02 17:48:20 -05:00
if(th.classList.contains("numeric")){
let arrayA = textA.replace('episodes: ','').replace('-',0).split("/");
let arrayB = textB.replace('episodes: ','').replace('-',0).split("/");
2022-01-02 17:48:20 -05:00
if(arrayA.length > 1) {
textA = parseInt(arrayA[0],10) / parseInt(arrayA[1],10);
textB = parseInt(arrayB[0],10) / parseInt(arrayB[1],10);
2022-01-02 17:48:20 -05:00
}
else{
textA = parseInt(arrayA[0],10);
textB = parseInt(arrayB[0],10);
2022-01-02 17:48:20 -05:00
}
}
else if (parseInt(textA, 10)) {
textA = parseInt(textA, 10);
2016-02-01 09:49:18 -05:00
textB = parseInt(textB, 10);
}
if (textA > textB) {
return 1;
}
if (textA < textB) {
return -1;
}
return 0;
};
2018-08-10 20:09:28 -04:00
const toggle = () => {
const c = order !== 'sorting-asc' ? 'sorting-asc' : 'sorting-desc';
2018-08-10 20:09:28 -04:00
th.className = (th.className.replace(order, '') + ' ' + c).trim();
return order = c;
2016-02-01 09:49:18 -05:00
};
2018-08-10 20:09:28 -04:00
const reset = () => {
th.classList.remove('sorting-asc', 'sorting-desc');
2018-08-10 20:09:28 -04:00
th.classList.add('sorting');
return order = '';
2016-02-01 09:49:18 -05:00
};
2018-08-10 20:09:28 -04:00
const onClickEvent = (e) => {
if (th && (cellIndex !== e.target.cellIndex)) {
reset();
2016-02-01 09:49:18 -05:00
}
2018-08-10 20:09:28 -04:00
th = e.target;
if (th.nodeName.toLowerCase() === 'th') {
cellIndex = th.cellIndex;
const tbody = th.offsetParent.getElementsByTagName('tbody')[0];
let rows = Array.from(tbody.rows);
2016-02-01 09:49:18 -05:00
if (rows) {
2018-08-10 20:09:28 -04:00
rows.sort(sort);
if (order === 'sorting-asc') {
2018-08-10 20:09:28 -04:00
rows.reverse();
2016-02-01 09:49:18 -05:00
}
2018-08-10 20:09:28 -04:00
toggle();
2016-02-01 09:49:18 -05:00
tbody.innerHtml = '';
2018-08-10 20:09:28 -04:00
rows.forEach(row => {
2016-02-01 09:49:18 -05:00
tbody.appendChild(row);
2018-08-10 20:09:28 -04:00
});
2016-02-01 09:49:18 -05:00
}
}
};
return {
2018-08-10 20:09:28 -04:00
init: () => {
2016-02-01 09:49:18 -05:00
let ths = document.getElementsByTagName('th');
2018-08-10 20:09:28 -04:00
let results = [];
for (let i = 0, len = ths.length; i < len; i++) {
let th = ths[i];
th.classList.add('sorting');
2022-01-02 17:48:20 -05:00
th.classList.add('testing');
2018-08-10 20:09:28 -04:00
results.push(th.onclick = onClickEvent);
2016-02-01 09:49:18 -05:00
}
2018-08-10 20:09:28 -04:00
return results;
2016-02-01 09:49:18 -05:00
}
};
})();
2016-02-01 09:49:18 -05:00
LightTableSorter.init();