-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
60 lines (49 loc) · 1.29 KB
/
index.js
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
59
60
import {getProperty} from 'dot-prop';
export default function sortOn(array, property, {locales, localeOptions} = {}) {
if (!Array.isArray(array)) {
throw new TypeError(`Expected type \`Array\`, got \`${typeof array}\``);
}
return [...array].sort((a, b) => {
let returnValue = 0;
[property].flat().some(element => {
let isDescending;
let x;
let y;
if (typeof element === 'function') {
x = element(a);
y = element(b);
} else if (typeof element === 'string') {
isDescending = element.charAt(0) === '-';
element = isDescending ? element.slice(1) : element;
x = getProperty(a, element);
y = getProperty(b, element);
} else {
x = a;
y = b;
}
if (x === y) {
returnValue = 0;
return false;
}
if (y !== 0 && !y) {
returnValue = isDescending ? 1 : -1;
return true;
}
if (x !== 0 && !x) {
returnValue = isDescending ? -1 : 1;
return true;
}
if (typeof x === 'string' && typeof y === 'string') {
returnValue = isDescending ? y.localeCompare(x, locales, localeOptions) : x.localeCompare(y, locales, localeOptions);
return returnValue !== 0;
}
if (isDescending) {
returnValue = x < y ? 1 : -1;
} else {
returnValue = x < y ? -1 : 1;
}
return true;
});
return returnValue;
});
}