Skip to content

Instantly share code, notes, and snippets.

@Yago
Created December 14, 2017 13:48
Show Gist options
  • Save Yago/2340edd045b13c5e6b07f875b7f3e375 to your computer and use it in GitHub Desktop.
Save Yago/2340edd045b13c5e6b07f875b7f3e375 to your computer and use it in GitHub Desktop.
Sort with a base and a secondary attribute
/**
* Sort with a base and a secondary attribute
*
* @param {Object} x - first object to compare
* @param {Object} y - second object to compare
* @param {string} m1 - base sort method
* @param {boolean} m1_asc - base method ascending
* @param {string} m2 - secondary sort method
* @param {boolean} m2_asc - secondary method ascending
* @returns {number} - sort comparison result
*/
sortProperties(x, y, m1, m1_asc, m2, m2_asc) {
const a = x[m1] || false;
const b = y[m1] || false;
const order = m1_asc ? [a, b] : [b, a];
const test = a && b ? order[0] - order[1] : a && !b ? -1 : 1;
if (undefined !== m2) {
const c = x[m2] || false;
const d = y[m2] || false;
const childOrder = m2_asc ? [c, d] : [d, c];
const childTest = c && d ? childOrder[0] - childOrder[1] : c && !d ? -1 : 1;
return test === 0 ? childTest : test;
}
return test;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment