forked from Tinkoff/utils.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstableSortBy.ts
More file actions
57 lines (49 loc) · 1.39 KB
/
stableSortBy.ts
File metadata and controls
57 lines (49 loc) · 1.39 KB
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
import { sort } from '../typings/types';
import curryN from '../function/curryN';
/**
* Sorts the array according to the supplied function and keeping the order of elements.
*
* @param {Function} fn
* @param {Array} arr The array to sort.
* @return {Array} A new array sorted by the keys generated by `fn`.
* @example
*
* const people = [
* { name: 'Ann', age: 20 },
* { name: 'Gary', age: 20 },
* { name: 'John', age: 17 },
* { name: 'Sam', age: 21 },
* { name: 'Bob', age: 17 }
* ];
* stableSortBy(path(['age']), people) => [
* { name: 'John', age: 17 },
* { name: 'Bob', age: 17 },
* { name: 'Ann', age: 20 },
* { name: 'Gary', age: 20 },
* { name: 'Sam', age: 21 }
* ]
*/
export default curryN(2, (fn, arr = []) => {
const len = arr.length;
const indexes = new Array(len);
for (let i = 0; i < len; i++) {
indexes[i] = i;
}
indexes.sort((a, b) => {
const valueA = arr[a];
const valueB = arr[b];
const x = fn(valueA);
const y = fn(valueB);
if (x < y) {
return -1;
} else if (x > y) {
return 1;
}
return a - b;
});
const result = new Array(len);
for (let i = 0; i < len; i++) {
result[i] = arr[indexes[i]];
}
return result;
}) as typeof sort