Created
April 2, 2012 21:56
-
-
Save michiel/2287509 to your computer and use it in GitHub Desktop.
Some sorting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Ex. sort on attrs = [ | |
// ["Name", "asc"], | |
// ["Description, "desc"] | |
// ] | |
// | |
// This is how we do just one column, | |
// | |
// function sortOn(objs, attr, order) { | |
// return objs.sort( | |
// function(a, b) { | |
// return (a.get(attr) > b.get(attr)) ? | |
// (order == "asc") ? 1 : -1 : -1 : 1; | |
// } | |
// ); | |
// } | |
// | |
// If only the next case was that simple. | |
// | |
// | |
// The following code is UNTESTED | |
// | |
function sort(objs, attrs) { | |
return dojo.map( | |
( | |
// | |
// This sets up Arrays in an Array to feed into Array.sort(sorter), | |
// [ | |
// [mxobj, value#attr[0], value#attr[1], ...], | |
// [mxobj, value#attr[0], value#attr[1], ...], | |
// ... | |
// ] | |
// | |
(dojo.map( objs, function(obj) { | |
var arr = [obj]; // ... and here's the hack that prevents usage of map | |
dojo.forEach(attrs, function(attr) { | |
arr.push(obj.get(attr[0])); | |
}); | |
return arr; | |
} | |
) | |
).sort( | |
function(attrsA, attrsB) { | |
// | |
// 0 contains the mxobj and yes that's a hack and why the loop starts at 1 | |
// Equality determination on a value/value basis is left up to the JS runtime. | |
// Here we just go over the values in order of precedence and return the | |
// appropriate -1 / 1 value if they're unequal at any point. | |
// (With an extra test for "asc"/"desc"). | |
// If there are no inequalities, we return with 0 (outside the for loop) | |
// | |
for (var i=1; i<attrs.length; i++) { | |
var a = attrsA[i], | |
b = attrsB[i]; | |
if (a == b) { | |
continue; // to next attribute | |
} else /* There is an inequality, so return now with the right value */ { | |
if (attrs[i][1] == "asc") { | |
return (a > b) ? 1 : -1; | |
} else { | |
return (a > b) ? -1 : 1; | |
} | |
// | |
// This could also be, | |
// return (attrs[i][1] == "asc") ? (a > b) ? 1 : -1 : -1 : 1; | |
// .. but there is a fine line between efficient and readable coding. | |
// | |
} | |
} | |
return 0; // The elements are equal | |
} | |
)), function(arr) { | |
return arr[0]; // Finally return an Array with only the mxobjs in the newly sorted order | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment