User:Najzere/listsort.js

// Author: Brian Huisman @ http://my.opera.com/GreyWyvern/blog/show.dml/1671288 // License: ?? seems to be open // Description: Alphanumeric sorting of highlighted, multi-line text lists. Each list item goes on a separate line with no blank lines in between. Then highlight the list and click for ascending or descending sort.

// Only add button when in edit mode if (wgAction == 'edit' || wgAction == 'submit') { addOnloadHook(addSortButtons); };

// Add buttons to toolbar set to perform sorting when clicked function addSortButtons { // Add ascending sort button var image = document.createElement('img'); image.width = 23; image.height = 22; image.className = 'mw-toolbar-editbutton'; image.id = 'sort-asc-button'; image.src = 'http://media.strategywiki.org/images/1/15/Button_sort-asc.png'; image.border = 0; image.title = 'Sort ascending'; image.style.cursor = 'pointer'; image.onclick = sortList(true); document.getElementById('toolbar').insertBefore(image, document.getElementById('toolbar').lastChild.nextSibling);

// Add descending sort button var image2 = document.createElement('img'); image2.width = 23; image2.height = 22; image2.className = 'mw-toolbar-editbutton'; image2.id = 'sort-desc-button'; image2.src = 'http://media.strategywiki.org/images/5/54/Button_sort-desc.png'; image2.border = 0; image2.title = 'Sort descending'; image2.style.cursor = 'pointer'; image2.onclick = sortList(false); document.getElementById('toolbar').insertBefore(image2, document.getElementById('toolbar').lastChild.nextSibling); };

function sortList(ascending) { var tbox = document.getElementById('tbox'); var startPos = tbox.selectionStart; var endPos = tbox.selectionEnd;

if (endPos-startPos>0) { var hilited = tbox.value.substring(startPos,endPos); if (hilited.search(/\n\n+/g) > -1) { alert("Please remove empty lines before sorting."); tbox.focus; return; };   var ulist = hilited.split('\n'); ulist.alphanumSort; if (ascending = false) { ulist.reverse; };   var slist = ulist.join('\n'); tbox.value = tbox.value.replace(hilited,slist); tbox.selectionStart = startPos; tbox.selectionEnd = endPos; tbox.focus; }; };

// Add alphanumSort method to Array object Array.prototype.alphanumSort = function(caseInsensitive) { for (var z = 0, t; t = this[z]; z++) { this[z] = []; var x = 0, y = -1, n = 0, i, j;

while (i = (j = t.charAt(x++)).charCodeAt(0)) { var m = (i == 46 || (i >=48 && i <= 57)); if (m !== n) { this[z][++y] = ""; n = m;     } this[z][y] += j;   } }

this.sort(function(a, b) {   for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {      if (caseInsensitive) {        aa = aa.toLowerCase;        bb = bb.toLowerCase;      }      if (aa !== bb) {        var c = Number(aa), d = Number(bb);        if (c == aa && d == bb) {          return c - d;        } else return (aa > bb) ? 1 : -1;      }    }    return a.length - b.length;  });

for (var z = 0; z < this.length; z++) this[z] = this[z].join(""); }