|
| 1 | +/** |
| 2 | + * Order should be a String (with the property name assumed ascending) |
| 3 | + * or an Array or property String names. |
| 4 | + * |
| 5 | + * Examples: |
| 6 | + * |
| 7 | + * 1. 'property1' (ORDER BY property1 ASC) |
| 8 | + * 2. '-property1' (ORDER BY property1 DESC) |
| 9 | + * 3. [ 'property1' ] (ORDER BY property1 ASC) |
| 10 | + * 4. [ '-property1' ] (ORDER BY property1 DESC) |
| 11 | + * 5. [ 'property1', 'A' ] (ORDER BY property1 ASC) |
| 12 | + * 6. [ 'property1', 'Z' ] (ORDER BY property1 DESC) |
| 13 | + * 7. [ '-property1', 'A' ] (ORDER BY property1 ASC) |
| 14 | + * 8. [ 'property1', 'property2' ] (ORDER BY property1 ASC, property2 ASC) |
| 15 | + * 9. [ 'property1', '-property2' ] (ORDER BY property1 ASC, property2 DESC) |
| 16 | + * ... |
| 17 | + */ |
| 18 | + |
| 19 | +exports.standardizeOrder = function (order) { |
| 20 | + if (typeof order == "string") { |
| 21 | + if (order[0] == "-") { |
| 22 | + return [ [ order.substr(1), "Z" ] ]; |
| 23 | + } |
| 24 | + return [ [ order, "A" ] ]; |
| 25 | + } |
| 26 | + |
| 27 | + var new_order = [], minus; |
| 28 | + |
| 29 | + for (var i = 0; i < order.length; i++) { |
| 30 | + minus = (order[i][0] == "-"); |
| 31 | + |
| 32 | + if (i < order.length - 1 && [ "A", "Z" ].indexOf(order[i + 1].toUpperCase()) >= 0) { |
| 33 | + new_order.push([ |
| 34 | + (minus ? order[i].substr(1) : order[i]), |
| 35 | + order[i + 1] |
| 36 | + ]); |
| 37 | + i += 1; |
| 38 | + } else if (minus) { |
| 39 | + new_order.push([ order[i].substr(1), "Z" ]); |
| 40 | + } else { |
| 41 | + new_order.push([ order[i], "A" ]); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return new_order; |
| 46 | +}; |
0 commit comments