Article 4WP4P CodeSOD: We Go to School

CodeSOD: We Go to School

by
Remy Porter
from The Daily WTF on (#4WP4P)

Sometimes, it feels like any programming question you might have has a thread on StackOverflow. It might not have an answer, but it's probably there. Between that, online guidebooks, tools with decent documentation, YouTube programming tutorials there are a lot of great ways to learn how to solve any given programming task.

Andreas R had a programming task. Specifically, Andreas wanted to create sortable tables that worked like those on MediaWiki sites. A quick google for "sort html table" turned up a source which offered" this.

function sortTable() { var table, rows, switching, i, x, y, shouldSwitch; table = document.getElementById("myTable"); switching = true; /* Make a loop that will continue until no switching has been done: */ while (switching) { // Start by saying: no switching is done: switching = false; rows = table.rows; /* Loop through all table rows (except the first, which contains table headers): */ for (i = 1; i < (rows.length - 1); i++) { // Start by saying there should be no switching: shouldSwitch = false; /* Get the two elements you want to compare, one from current row and one from the next: */ x = rows[i].getElementsByTagName("TD")[0]; y = rows[i + 1].getElementsByTagName("TD")[0]; // Check if the two rows should switch place: if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) { // If so, mark as a switch and break the loop: shouldSwitch = true; break; } } if (shouldSwitch) { /* If a switch has been marked, make the switch and mark that a switch has been done: */ rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); switching = true; } }}

This code works, for very limited values of "works". It works by doing a bubble sort until we stop swapping entries. It always skips the first row, under the assumption that we're looking at a table with headers. It only ever sorts by the first column. It does all the sorting directly in the DOM, which is a great way to really add some overhead to your data manipulation.

There are a lot of shady, skeevy tutorial sites, and some of them are really good at search engine optimization. This is one of those. It's the sort of site anyone with any experience knows is a bad source, but those without that experience are left to learn the hard way.

TRWTF are sites that spend more time and energy on SEO than on providing helpful content. At least when we share bad code, we know it's bad- and so does our audience.

buildmaster-icon.png [Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how! TheDailyWtf?d=yIl2AUoC8zAo3Dwx7pg2hc
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments