Last active
January 23, 2023 17:35
-
-
Save wpcarro/fc99b0a005f52eca5c76a834f19b1027 to your computer and use it in GitHub Desktop.
Simple DSL for composing sorting logic
This file contains 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
// 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