Skip to content

Commit 51d7781

Browse files
committed
feat(sortby): add sortBy function
1 parent 089fded commit 51d7781

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

index.test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import {
4949
scanRight1,
5050
slice,
5151
sort,
52+
sortBy,
5253
split,
5354
sum,
5455
tail,
@@ -514,6 +515,30 @@ test("sort", t => {
514515
);
515516
});
516517

518+
test("sortBy", t => {
519+
t.deepEqual(
520+
sortBy(
521+
[
522+
{x: "a", y: 2},
523+
{x: "b", y: 4},
524+
{x: "c", y: 3},
525+
{x: "d", y: 1}
526+
],
527+
({y}) => y
528+
),
529+
[
530+
{x: "d", y: 1},
531+
{x: "a", y: 2},
532+
{x: "c", y: 3},
533+
{x: "b", y: 4}
534+
]
535+
);
536+
t.deepEqual(
537+
sortBy([-2, 4, -3, 1], e => Math.abs(e)),
538+
[1, -2, -3, 4]
539+
);
540+
});
541+
517542
test("forEach", t => {
518543
const a = ["a", "b", "c"];
519544
let s = "";

index.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1524,6 +1524,19 @@ export function sortFn<T>(comparator: Comparator<T>): (array: ArrayLike<T>) => T
15241524
return array => sort(array, comparator);
15251525
}
15261526

1527+
export function sortBy<T>(array: ArrayLike<T>, select: SortSelect<T>): T[] {
1528+
return sort(array, (a, b) => defaultCompare(select(a) as any, select(b) as any));
1529+
}
1530+
1531+
export type SortSelect<T> =
1532+
| ((element: T) => boolean)
1533+
| ((element: T) => number)
1534+
| ((element: T) => string);
1535+
1536+
export function sortByFn<T>(select: SortSelect<T>): (array: ArrayLike<T>) => T[] {
1537+
return array => sortBy(array, select);
1538+
}
1539+
15271540
export function forEach<T>(
15281541
array: ArrayLike<T>,
15291542
f: (element: T, index: number) => void

0 commit comments

Comments
 (0)