Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Stack Overflow Random Answer Sort Tab
// ==UserScript==
// @name Stack Overflow Random Answer Sort Tab
// @namespace https://github.com/edcottrell/
// @version 0.1.2
// @description Add a "random" tab for sorting Stack Overflow answers
// @author Ed Cottrell
// @license MIT
// @match *://*.askubuntu.com/*
// @match *://*.mathoverflow.net/*
// @match *://*.serverfault.com/*
// @match *://*.stackapps.com/*
// @match *://*.stackexchange.com/*
// @match *://*.stackoverflow.com/*
// @match *://*.superuser.com/*
// @exclude *://data.stackexchange.com/*
// @exclude *://stackexchange.com/users/*
// @grant none
// ==/UserScript==
// set up some variables
var $answers = jQuery('div.answer'),
arrayIndex,
newOrder = [],
prop,
randomWeights = {},
relativeUrl = window.location.href.replace(/^.+\/\/.+?\//, '\/'),
selectedTab = window.location.href.replace(/.+?answertab=([^&#]+).*/, '$1'),
tabUrl = relativeUrl.replace(/([?&]answertab=)[^&#]+/, '$1random')
;
// make sure the URL has an answertab parameter
if (!tabUrl.match(/([?&]answertab=)[^&#]+/)) {
tabUrl = (tabUrl + '?answertab=random').replace(/(\?.+)\?/, '$1&');
}
// add a random sort tab
jQuery('#tabs a[data-value="oldest"]').after('<a href="' + tabUrl + '" title="Random" data-value="random" data-nav-xhref="">random</a>');
if (selectedTab === 'random') {
// fix the tab highlighting
jQuery('.youarehere').removeClass('youarehere');
jQuery('a[title="Random"]').addClass('youarehere');
// give each answer a random "weight" for sorting
$answers.each(function (x) {
randomWeights[$(this).prop('id').replace(/answer-/, '')] = Math.random();
});
// sort the ids by weight
for (prop in randomWeights) {
newOrder.push(prop);
}
newOrder.sort(
function(a,b) {
return randomWeights[a] > randomWeights[b] ? 1 : (randomWeights[a] == randomWeights[b] ? 0 : -1);
}
);
// remove the anchor tags and answers and append them in the right order
for (arrayIndex = 0; arrayIndex < newOrder.length; arrayIndex++) {
$('a[name=' + newOrder[arrayIndex] + ']')
.detach()
.appendTo('div#answers');
$('div#answer-' + newOrder[arrayIndex])
.detach()
.appendTo('div#answers');
}
// reset locations of the non-answer elements of the #answers div
$('#answers a[name="new-answer"]')
.detach()
.appendTo('div#answers');
$('#post-form')
.detach()
.appendTo('div#answers');
$('#show-editor-button')
.detach()
.appendTo('div#answers');
$('#answers .bottom-notice')
.detach()
.appendTo('div#answers');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment