(arg, req)
| 30 | * @returns {*} The sorted data or original data if not sortable |
| 31 | */ |
| 32 | export function sort (arg, req) { |
| 33 | // Handle undefined input |
| 34 | if (arg === undefined) { |
| 35 | return undefined; |
| 36 | } |
| 37 | |
| 38 | // Handle missing properties - early return |
| 39 | if (!req?.parsed?.searchParams || typeof req.parsed.search !== STRING) { |
| 40 | return smartClone(arg); |
| 41 | } |
| 42 | |
| 43 | if (!req.parsed.searchParams.has(ORDER_BY) || !Array.isArray(arg)) { |
| 44 | return smartClone(arg); |
| 45 | } |
| 46 | |
| 47 | const type = typeof arg[INT_0]; |
| 48 | |
| 49 | // Early return for non-sortable arrays |
| 50 | if (type === BOOLEAN || type === NUMBER || type === STRING || type === UNDEFINED || arg[INT_0] === null) { |
| 51 | return smartClone(arg); |
| 52 | } |
| 53 | |
| 54 | const allOrderByValues = req.parsed.searchParams.getAll(ORDER_BY); |
| 55 | |
| 56 | // Process order_by values more efficiently |
| 57 | const orderByValues = []; |
| 58 | let hasDesc = false; |
| 59 | let lastNonDescIndex = -1; |
| 60 | |
| 61 | for (let i = 0; i < allOrderByValues.length; i++) { |
| 62 | const value = allOrderByValues[i]; |
| 63 | if (value === DESC) { |
| 64 | hasDesc = true; |
| 65 | } else if (value.trim() !== "") { |
| 66 | orderByValues.push(value); |
| 67 | lastNonDescIndex = i; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // Clone only once when we know we need to sort |
| 72 | let output = smartClone(arg); |
| 73 | |
| 74 | // Apply sorting if we have valid order_by values |
| 75 | if (orderByValues.length > INT_0) { |
| 76 | const args = orderByValues.join(COMMA_SPACE); |
| 77 | output = keysort(output, args); |
| 78 | } |
| 79 | |
| 80 | // Handle reverse logic efficiently |
| 81 | if (hasDesc) { |
| 82 | const descIndex = allOrderByValues.indexOf(DESC); |
| 83 | const hasOtherKeys = orderByValues.length > INT_0; |
| 84 | |
| 85 | if (descIndex > lastNonDescIndex || !hasOtherKeys) { |
| 86 | output = output.reverse(); |
| 87 | } |
| 88 | } |
| 89 |
no test coverage detected