* Copied from https://github.com/angular/components/blob/main/src/material/table/table-data-source.ts * License: MIT * Copyright (c) 2022 Google LLC. * * Gets a sorted copy of the data array based on the state of the MatSort. Called * after changes are made to the filtered data or whe
(data: T[], sort: Sort)
| 157 | * @param sort The connected MatSort that holds the current sort state. |
| 158 | */ |
| 159 | protected sortData(data: T[], sort: Sort): T[] { |
| 160 | const column = sort.column; |
| 161 | const directionModifier = sort.direction === "asc" ? 1 : -1; |
| 162 | if (!column) { |
| 163 | return data; |
| 164 | } |
| 165 | |
| 166 | return data.sort((a, b) => { |
| 167 | // If a custom sort function is provided, use it instead of the default. |
| 168 | if (sort.fn) { |
| 169 | return sort.fn(a, b, sort.direction) * directionModifier; |
| 170 | } |
| 171 | |
| 172 | let valueA = this.sortingDataAccessor(a, column); |
| 173 | let valueB = this.sortingDataAccessor(b, column); |
| 174 | |
| 175 | // If there are data in the column that can be converted to a number, |
| 176 | // it must be ensured that the rest of the data |
| 177 | // is of the same type so as not to order incorrectly. |
| 178 | const valueAType = typeof valueA; |
| 179 | const valueBType = typeof valueB; |
| 180 | |
| 181 | if (valueAType !== valueBType) { |
| 182 | if (valueAType === "number") { |
| 183 | valueA += ""; |
| 184 | } |
| 185 | if (valueBType === "number") { |
| 186 | valueB += ""; |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | if (typeof valueA === "string" && typeof valueB === "string") { |
| 191 | return valueA.localeCompare(valueB) * directionModifier; |
| 192 | } |
| 193 | |
| 194 | // If both valueA and valueB exist (truthy), then compare the two. Otherwise, check if |
| 195 | // one value exists while the other doesn't. In this case, existing value should come last. |
| 196 | // This avoids inconsistent results when comparing values to undefined/null. |
| 197 | // If neither value exists, return 0 (equal). |
| 198 | let comparatorResult = 0; |
| 199 | if (valueA != null && valueB != null) { |
| 200 | // Check if one value is greater than the other; if equal, comparatorResult should remain 0. |
| 201 | if (valueA > valueB) { |
| 202 | comparatorResult = 1; |
| 203 | } else if (valueA < valueB) { |
| 204 | comparatorResult = -1; |
| 205 | } |
| 206 | } else if (valueA != null) { |
| 207 | comparatorResult = 1; |
| 208 | } else if (valueB != null) { |
| 209 | comparatorResult = -1; |
| 210 | } |
| 211 | |
| 212 | return comparatorResult * directionModifier; |
| 213 | }); |
| 214 | } |
| 215 | |
| 216 | /** |
no test coverage detected