Skip to content

Instantly share code, notes, and snippets.

@michiel
Created April 2, 2012 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michiel/2287509 to your computer and use it in GitHub Desktop.
Save michiel/2287509 to your computer and use it in GitHub Desktop.
Some sorting
//
// 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