Created
December 12, 2018 10:11
-
-
Save pokidovea/bd9bd4826fa9e7f368b4a6d5ce407bdb to your computer and use it in GitHub Desktop.
Multiple fields comparator
This file contains hidden or 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
export function compareByField(field, reverse, predicate) { | |
const key = predicate ? x => predicate(x[field]) : x => x[field] | |
reverse = !reverse ? 1 : -1 | |
return (a, b) => { | |
const key_a = key(a) | |
const key_b = key(b) | |
return reverse * ((key_a > key_b) - (key_b > key_a)) | |
} | |
} | |
/* | |
Params description: | |
sortingRules = [ | |
{columnName: 'field1', 'direction': 'asc'}, | |
{columnName: 'field2', 'direction': 'desc'}, | |
] | |
predicates = { | |
'field1': (value) => value.toLowerCase() | |
} | |
*/ | |
export function compareByMultipleFields(sortingRules, predicates) { | |
let comparators = sortingRules.map(sortingRule => { | |
return compareByField( | |
sortingRule.columnName, | |
sortingRule.direction === 'desc', | |
predicates[sortingRule.columnName] || null | |
) | |
}) | |
return (a, b) => { | |
for (let comparator of comparators) { | |
const comparisonResult = comparator(a, b) | |
if (comparisonResult !== 0) return comparisonResult | |
} | |
return 0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment