Skip to content

Instantly share code, notes, and snippets.

@jeremypage
Last active April 24, 2019 06:03
Show Gist options
  • Save jeremypage/db8f38e682ef91155e250b5049ed740a to your computer and use it in GitHub Desktop.
Save jeremypage/db8f38e682ef91155e250b5049ed740a to your computer and use it in GitHub Desktop.
jsTree: Custom sort - Specify priority entries that must always be listed first, and the order they must appear
// Example usage:
// $("#EstablishmentTree").jstree({
// // other jstree properties ...
// "sort": // function sort(a, b) { ... }
// });
function sort(a, b) {
// For jsTree, use get_text() to get node text:
// var textA = this.get_text(a), textB = this.get_text(b);
var textA = a,
textB = b;
// Terms that should always be listed first, and the order they should appear
var priorityTerms = ["This always comes first", "ZZZ alphabetically last, but still in priority list", "Alphabetically first, but third in priority list"];
var indexOfTextA = priorityTerms.indexOf(textA),
indexOfTextB = priorityTerms.indexOf(textB);
return (indexOfTextA > -1 && indexOfTextB > -1) ? (indexOfTextA > indexOfTextB) ? 1 : -1
: (indexOfTextA > -1) ? -1 : (indexOfTextB > -1) ? 1
: (textA > textB) ? 1 : -1 // default alpha sort
}
// Uncomment for Jest testing
// module.exports = sort;
/*
Jest tests: That custom sort(a,b) function in jstree-sort.js returns expected value
If first item comes before second item (when sorted alphanumerically)
then return -1,
else return 1
https://jestjs.io/
*/
const sort = require('./sort');
test.each([
["A", "Z", -1],
["Z", "A", 1],
["A", "This always comes first", 1],
["This always comes first", "A", -1],
["This always comes first", "Alphabetically first, but third in priority list", -1],
["ZZZ alphabetically last, but still in priority list", "Alphabetically first, but third in priority list", -1]
])(
"'%s' is before '%s' == %i",
(a, b, expected) => {
expect(sort(a, b)).toBe(expected);
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment