Skip to content

Instantly share code, notes, and snippets.

@wpcarro
Last active January 23, 2023 17:35
Show Gist options
  • Save wpcarro/fc99b0a005f52eca5c76a834f19b1027 to your computer and use it in GitHub Desktop.
Save wpcarro/fc99b0a005f52eca5c76a834f19b1027 to your computer and use it in GitHub Desktop.
Simple DSL for composing sorting logic
// Convert a sorting expressions (e.g. "Outflow DESC; Date ASC; Category ASC")
// into a function that can be passed to Array.prototype.sort.
function compileSort(expr) {
if (expr === '') {
return function(x, y) { return 0; };
}
return expr.split(/\s*;\s*/).reverse().reduce((acc, x) => {
const [k, dir] = x.split(/\s+/);
if (dir === 'ASC') {
return function(x, y) {
if (x[k] > y[k]) { return 1; }
if (x[k] < y[k]) { return -1; }
else { return acc(x, y); }
};
}
if (dir === 'DESC') {
return function(x, y) {
if (x[k] > y[k]) { return -1; }
if (x[k] < y[k]) { return 1; }
else { return acc(x, y); }
};
}
else {
throw new Error(`Sort direction not supported, ${dir}, must be either "ASC" or "DESC"`);
}
}, function(x, y) { return 0; })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment