Skip to content

Instantly share code, notes, and snippets.

@abozhilov
Created July 20, 2016 11:11
Show Gist options
  • Save abozhilov/7148438be597e67c4fb6701703eb14a0 to your computer and use it in GitHub Desktop.
Save abozhilov/7148438be597e67c4fb6701703eb14a0 to your computer and use it in GitHub Desktop.
var sort = (function () {
function defCompare(a, b) {
var aStr = String(a),
bStr = String(b);
if (aStr > bStr) {
return 1;
}
else if (aStr < bStr) {
return -1;
}
else {
return 0;
}
}
function isSorted(arr, compareFunc) {
if (typeof compareFunc == 'undefined') {
compareFunc = defCompare;
}
for (var i = 1, len = arr.length; i < len; i++) {
if (compareFunc(arr[i - 1], arr[i]) > 0) {
return false;
}
}
return true;
}
return function (arr, compareFunc) {
if (!isSorted(arr, compareFunc)) {
return arr.slice().sort(compareFunc);
}
return arr.slice();
}
})();
function comparator(a, b) {
return a - b;
}
var arr = [];
for (var i = 0; i < 1e6; i++) {
arr.push(i);
}
var time = new Date();
sort(arr, comparator);
time = new Date() - time;
console.log(time);
var time = new Date();
arr.sort(comparator);
time = new Date() - time;
console.log(time);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment