es-toolkit
es-toolkit copied to clipboard
Support custom key functions in `es-toolkit/orderBy` and `es-toolkit/compat/orderBy`
Problems
- At now, we have a custom key function in
sortBy, butorderBydoesn't have this feature.
Maybe, this makes confusion.
lodash/orderByalso supports this feature, but oures-toolkit/compat/orderBydoesn't support it.
Solutions
- Add it in
es-toolkit/orderBy. - Add it in
es-toolkit/compat/orderBy.
But after we also supports it in es-toolkit/orderBy, then es-toolkit/orderBy looks like duplication of es-toolkit/sortBy.
Difference of these functions is just it has a
orderargument or not.
So I think we have to integrate codes of these functions.
Related issue
https://github.com/toss/es-toolkit/issues/361#issuecomment-2280358793 I guess in this case, the ideal way of using
orderBywould be:orderBy(data, x => x.value.toString(), ["asc"])This would ensure that all numbers and strings are converted into string before comparison.
If this issue is acceptable, then I will work separately.
At first, I will make a PR for supporting custom key functions in es-toolkit/compat/orderBy.
And a rest of PR is for supporting it in es-toolkit/orderBy and integrating with a es-toolkit/sortBy
If we add this feature in es-toolkit/orderBy, then how about makes orderBy deprecated and add a orders arguments in sortBy.
Two functions is too similar.
We might support both sortBy and orderBy, even though they’re pretty similar.
sortBy usually sorts in ascending order, like Array#sort. If we need to sort in descending order, that’s where orderBy comes in.
We might support both
sortByandorderBy, even though they’re pretty similar.
sortByusually sorts in ascending order, likeArray#sort. If we need to sort in descending order, that’s whereorderBycomes in.
Almost programming languages have one sort function that has a reverse option, And javascript also have one sort function that has custom compare function. So I can't understand that we support both sortBy and orderBy in es-toolkit.
But if we decide to support both orderBy and sortBy, then we can change sortBy code like:
export function sortBy<T extends object>(arr: T[], criteria: Array<((item: T) => unknown) | keyof T>): T[] {
return orderBy(arr, criteria, ['asc']);
// or return orderBy(arr, criteria, criteria.map(() => 'asc');
}
If this is ok, then I will create PR for supporting custom key functions in orderBy and changing sortBy codes to above codes.
I think what the direction of what you suggested is great.
I closed the related PR by mistake. I will open the same PR soon.