Skip to content

Instantly share code, notes, and snippets.

@ferdaber
Created March 6, 2019 19:39
Show Gist options
  • Save ferdaber/e33dd772bb9880dcd87adf4e625d82d7 to your computer and use it in GitHub Desktop.
Save ferdaber/e33dd772bb9880dcd87adf4e625d82d7 to your computer and use it in GitHub Desktop.
Sorting with priority
const prioritizedVals = {
a: 0,
b: 1,
c: 2
}
function sortWithPriority(a, b) {
// if it's not a prioritized value the sort value is Infinity and falls back to default sorting
const s1 = prioritizedVals[a] || Infinity
const s2 = prioritizedVals[b] || Infinity
// s1 - s2 will return NaN when both s1 and s2 are Infinity which is falsy, and falls back to the default sorting
// s1 and s2 will be a negative number (-Infinity) if s2 is not a prioritized value which puts a before b
// s1 and s2 will be a positive number (Infinity) if s1 is not a prioritized value which puts a after b
// s1 and s2 will do proper math when they are both prioritized values
return s1 - s2 || a < b ? -1 : a > b ? 1 : 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment