User:Phe/Sort author.js

From Wikisource
Jump to navigation Jump to search
Note: After saving, changes may not occur immediately. Click here to learn how to bypass your browser's cache.
  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Cmd-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (Cmd-Shift-R on a Mac)
  • Internet Explorer: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Clear the cache in Tools → Preferences

For details and instructions about other browsers, see Wikipedia:Bypass your cache.

function get_sort_key(a)
{
    var expr = new RegExp("\\[\\[Author:.*\\|(.*)\\]\\]");
    a = expr.exec(a)[1];

    a = a.replace(/[XIV]+, Pope$/, '');

    a = a.split(',');
    for (var i = 0; i < a.length; ++i) {
        a[i] = a[i].replace(/^ */, '')
        a[i] = a[i].replace(/ *$/, '')
        a[i] = a[i].replace(/'/g, '');
        a[i] = a[i].replace(/^Sir /, '');
        a[i] = a[i].replace(/^Captain /, '');
        a[i] = a[i].replace(/^Rev\. /, '');
        a[i] = a[i].replace(/^Lord /, '');
        a[i] = a[i].replace(/^de /, '');
        a[i] = a[i].replace(/^du /, '');
        a[i] = a[i].replace(/^von /, '');
        a[i] = a[i].replace(/^van /, '');
    }

   return a;
}

function compare_author(a, b)
{
   var date_a = a.replace(/.*\((\d+).*/, '$1');
   var date_b = b.replace(/.*\((\d+).*/, '$1');
   a = get_sort_key(a);
   b = get_sort_key(b);
   for (var i = 0; i < (a.length < b.length ? a.length : b.length); ++i) {
       var ret = a[i].toLowerCase().localeCompare(b[i].toLowerCase());
       if (ret != 0)
           return ret;
   }
   return Number(date_a) - Number(date_b);
}

function sort_author()
{
    var wpTextbox1 = document.getElementById("wpTextbox1");
    if (!wpTextbox1)
        return;
    var text = wpTextbox1.value.substring(8);
    var header = wpTextbox1.value.substring(0, 7);
    text = text.split('*');
    text.sort(compare_author);
    text = text.join('*');
    wpTextbox1.value = header + '*' + text;
}