Skip to content

Commit

Permalink
feat: add sort shorthand that accepts a property name to sort by
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jun 27, 2024
1 parent 262a263 commit cbb3fab
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/array/sort.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { ComparedValue, compare, flip } from 'radashi'

/**
* Sort an array without modifying it and return the newly sorted
* value
Expand All @@ -15,13 +17,12 @@
*/
export function sort<T>(
array: readonly T[],
getter: (item: T) => number,
getter: ComparedValue<T>,
desc = false,
): T[] {
if (!array) {
return []
}
const asc = (a: T, b: T) => getter(a) - getter(b)
const dsc = (a: T, b: T) => getter(b) - getter(a)
return array.slice().sort(desc === true ? dsc : asc)
const cmp = compare(getter)
return array.slice().sort(desc ? flip(cmp) : cmp)
}

0 comments on commit cbb3fab

Please sign in to comment.