source: node_modules/es-toolkit/dist/compat/array/orderBy.mjs@ ba17441

Last change on this file since ba17441 was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 2.6 KB
Line 
1import { compareValues } from '../_internal/compareValues.mjs';
2import { isKey } from '../_internal/isKey.mjs';
3import { toPath } from '../util/toPath.mjs';
4
5function orderBy(collection, criteria, orders, guard) {
6 if (collection == null) {
7 return [];
8 }
9 orders = guard ? undefined : orders;
10 if (!Array.isArray(collection)) {
11 collection = Object.values(collection);
12 }
13 if (!Array.isArray(criteria)) {
14 criteria = criteria == null ? [null] : [criteria];
15 }
16 if (criteria.length === 0) {
17 criteria = [null];
18 }
19 if (!Array.isArray(orders)) {
20 orders = orders == null ? [] : [orders];
21 }
22 orders = orders.map(order => String(order));
23 const getValueByNestedPath = (object, path) => {
24 let target = object;
25 for (let i = 0; i < path.length && target != null; ++i) {
26 target = target[path[i]];
27 }
28 return target;
29 };
30 const getValueByCriterion = (criterion, object) => {
31 if (object == null || criterion == null) {
32 return object;
33 }
34 if (typeof criterion === 'object' && 'key' in criterion) {
35 if (Object.hasOwn(object, criterion.key)) {
36 return object[criterion.key];
37 }
38 return getValueByNestedPath(object, criterion.path);
39 }
40 if (typeof criterion === 'function') {
41 return criterion(object);
42 }
43 if (Array.isArray(criterion)) {
44 return getValueByNestedPath(object, criterion);
45 }
46 if (typeof object === 'object') {
47 return object[criterion];
48 }
49 return object;
50 };
51 const preparedCriteria = criteria.map((criterion) => {
52 if (Array.isArray(criterion) && criterion.length === 1) {
53 criterion = criterion[0];
54 }
55 if (criterion == null || typeof criterion === 'function' || Array.isArray(criterion) || isKey(criterion)) {
56 return criterion;
57 }
58 return { key: criterion, path: toPath(criterion) };
59 });
60 const preparedCollection = collection.map(item => ({
61 original: item,
62 criteria: preparedCriteria.map((criterion) => getValueByCriterion(criterion, item)),
63 }));
64 return preparedCollection
65 .slice()
66 .sort((a, b) => {
67 for (let i = 0; i < preparedCriteria.length; i++) {
68 const comparedResult = compareValues(a.criteria[i], b.criteria[i], orders[i]);
69 if (comparedResult !== 0) {
70 return comparedResult;
71 }
72 }
73 return 0;
74 })
75 .map(item => item.original);
76}
77
78export { orderBy };
Note: See TracBrowser for help on using the repository browser.