-
Notifications
You must be signed in to change notification settings - Fork 576
/
sort_by.ts
58 lines (52 loc) · 1.21 KB
/
sort_by.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
/**
* Returns all elements in the given collection, sorted stably by their result using the given selector
*
* Example:
*
* ```ts
* import { sortBy } from "./sort_by.ts"
* import { assertEquals } from "../testing/asserts.ts";
*
* const people = [
* { name: 'Anna', age: 34 },
* { name: 'Kim', age: 42 },
* { name: 'John', age: 23 },
* ]
* const sortedByAge = sortBy(people, it => it.age)
*
* assertEquals(sortedByAge, [
* { name: 'John', age: 23 },
* { name: 'Anna', age: 34 },
* { name: 'Kim', age: 42 },
* ])
* ```
*/
export function sortBy<T>(
array: Array<T>,
selector:
| ((el: T) => number)
| ((el: T) => string)
| ((el: T) => bigint)
| ((el: T) => Date),
): Array<T> {
return Array.from(array).sort((a, b) => {
const selectedA = selector(a);
const selectedB = selector(b);
if (typeof selectedA === "number") {
if (Number.isNaN(selectedA)) {
return 1;
}
if (Number.isNaN(selectedB)) {
return -1;
}
}
if (selectedA > selectedB) {
return 1;
}
if (selectedA < selectedB) {
return -1;
}
return 0;
});
}