Created
May 7, 2025 21:05
-
-
Save roschlau/4247f181bd2bf800e8619b09e14ad39e to your computer and use it in GitHub Desktop.
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
/** | |
* 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