Skip to content

Instantly share code, notes, and snippets.

@roschlau
Created May 7, 2025 21:05
Show Gist options
  • Save roschlau/4247f181bd2bf800e8619b09e14ad39e to your computer and use it in GitHub Desktop.
Save roschlau/4247f181bd2bf800e8619b09e14ad39e to your computer and use it in GitHub Desktop.
/**
* Utility function to sort elements by some nested property or another calculated value. Meant to fix JavaScript
* missing a built-in `sortedBy` function like Kotlin has.
* @example
* people.sort(by(person => person.age))
* @param accessor a function that should return the value to sort by if called on an element
*/
export const by: <T>(accessor: (element: T) => string | number) => (a: T, b: T) => number = (accessor) =>
(a, b) => {
const aValue = accessor(a)
const bValue = accessor(b)
if (aValue < bValue) {
return -1
}
if (aValue > bValue) {
return 1
}
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment