Sort Tests
testing sorting of different kinds
by bladnman
HTML
<script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script src="http://www.bladnman.com/js/mbmJSUtilities.js"></script>
<script src="http://www.bladnman.com/js/MMStopWatch.js"></script>
<script src="http://www.bladnman.com/js/MMPhraseGenerator.js"></script>
<input type=button id="theButton" value="run test" class="runButton">
<input type=button id="showArray" value="Show Array" class="runButton">
<div id="log" class="log"></div>
CSS
.runButton {
width: 125px;
margin: 20px;
}
.log {
padding:10px;
margin: 20px;
border: 1px dotted #ccc;
color:#888;
font-face: arial;
font-size:14px;
background: #fbfbfb;
}
JavaScript
/* ************************************ */
var countToTest = 50000;
var stringLengths = 10;
var items = [];
function runTest() {
sortStandard();
sortByString();
sortByStringCaseInsensitive();
}
// ------------------------
function sortStandard() {
ddebug();
populateArrayWithNames();
MMStopWatch.start("Sort standard");
items.sort(dynamicSort("value"));
ddebug(MMStopWatch.stop("Sort standard"));
}
function sortByString() {
ddebug();
populateArrayWithNames();
MMStopWatch.start("Sort standard");
var ascending = true;
items.sort(sort_string_by("value", ascending, true));
ddebug(MMStopWatch.stop("Sort standard"));
}
function sortByStringCaseInsensitive() {
ddebug();
populateArrayWithNames();
MMStopWatch.start("Sort standard case insensitive");
var ascending = true;
items.sort(sort_string_by("value", ascending, false));
ddebug(MMStopWatch.stop("Sort standard case insensitive"));
}
function sort_string_by(field, isAscending, isCaseInsensitive) {
return function (a, b) {
var aValue = getStringValue( a[field] );
var bValue = getStringValue( b[field] );
if (isCaseInsensitive) {
aValue = aValue.toLowerCase();
bValue = bValue.toLowerCase();
}
return ((aValue < bValue) ? -1 : (aValue > bValue) ? +1 : 0) * [-1,1][+!! isAscending];
};
}
function dynamicSort(property) {
return function (a,b) {
return (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
}
}
function populateArrayWithNames() {
MMStopWatch.start("PopulateArray");
if (items.length > 0) {
items.clear;
}
for (var x = 0; x < countToTest; x++) {
var item = {};
item.value = MMPhraseGenerator.name();
items[x] = item;
}
...