UNPKG

1.07 kBJavaScriptView Raw
1var arraySortBy = sortBy;
2
3function handleSort(iteratee) {
4 return function(a, b) {
5 var keyA = typeof iteratee === 'string' ? a[iteratee] : iteratee(a);
6 var keyB = typeof iteratee === 'string' ? b[iteratee] : iteratee(b);
7
8 if (typeof keyA === 'string' && typeof keyB === 'string') {
9 var valueA = keyA.toUpperCase();
10 var valueB = keyB.toUpperCase();
11
12 if (valueA < valueB) {
13 return -1;
14 }
15
16 if (valueA > valueB) {
17 return 1;
18 }
19
20 return 0;
21 }
22
23 return keyA - keyB;
24 };
25}
26
27function sortBy(arr, iteratee) {
28 if (!Array.isArray(arr)) {
29 throw new Error('arr should be an array');
30 }
31
32 if (iteratee !== undefined && (typeof iteratee !== 'string' && typeof iteratee !== 'function')) {
33 throw new Error('iteratee should be a string or a function');
34 }
35
36 if (arr.length <= 1) {
37 return arr;
38 }
39
40 var copied = arr.slice();
41
42 if (!iteratee) {
43 return copied.sort(function(a, b) {
44 return a - b;
45 });
46 }
47
48 return copied.sort(handleSort(iteratee));
49}
50
51export {arraySortBy as default};