Skip to content

Commit

Permalink
feat(sortby): add sortBy function
Browse files Browse the repository at this point in the history
  • Loading branch information
djcsdy committed Jan 13, 2022
1 parent 089fded commit 51d7781
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
25 changes: 25 additions & 0 deletions index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import {
scanRight1,
slice,
sort,
sortBy,
split,
sum,
tail,
Expand Down Expand Up @@ -514,6 +515,30 @@ test("sort", t => {
);
});

test("sortBy", t => {
t.deepEqual(
sortBy(
[
{x: "a", y: 2},
{x: "b", y: 4},
{x: "c", y: 3},
{x: "d", y: 1}
],
({y}) => y
),
[
{x: "d", y: 1},
{x: "a", y: 2},
{x: "c", y: 3},
{x: "b", y: 4}
]
);
t.deepEqual(
sortBy([-2, 4, -3, 1], e => Math.abs(e)),
[1, -2, -3, 4]
);
});

test("forEach", t => {
const a = ["a", "b", "c"];
let s = "";
Expand Down
13 changes: 13 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1524,6 +1524,19 @@ export function sortFn<T>(comparator: Comparator<T>): (array: ArrayLike<T>) => T
return array => sort(array, comparator);
}

export function sortBy<T>(array: ArrayLike<T>, select: SortSelect<T>): T[] {
return sort(array, (a, b) => defaultCompare(select(a) as any, select(b) as any));
}

export type SortSelect<T> =
| ((element: T) => boolean)
| ((element: T) => number)
| ((element: T) => string);

export function sortByFn<T>(select: SortSelect<T>): (array: ArrayLike<T>) => T[] {
return array => sortBy(array, select);
}

export function forEach<T>(
array: ArrayLike<T>,
f: (element: T, index: number) => void
Expand Down

0 comments on commit 51d7781

Please sign in to comment.