| 285 | } |
| 286 | |
| 287 | public sort<U>(key?: ArrayFunc<T, U>, direction?: "asc" | "desc", comparator?: ArrayComparator<U>): DataArray<T> { |
| 288 | if (this.values.length == 0) return this; |
| 289 | let realComparator = comparator ?? this.defaultComparator; |
| 290 | let realKey = key ?? ((l: T) => l as unknown as U); |
| 291 | |
| 292 | // Associate each entry with it's index for the key function, and then do a normal sort. |
| 293 | let copy = ([] as T[]).concat(this.array()).map((elem, index) => { |
| 294 | return { index: index, value: elem }; |
| 295 | }); |
| 296 | copy.sort((a, b) => { |
| 297 | let aKey = realKey(a.value, a.index, this.values); |
| 298 | let bKey = realKey(b.value, b.index, this.values); |
| 299 | return direction === "desc" ? -realComparator(aKey, bKey) : realComparator(aKey, bKey); |
| 300 | }); |
| 301 | |
| 302 | return this.lwrap(copy.map((e) => e.value)); |
| 303 | } |
| 304 | |
| 305 | public sortInPlace<U>( |
| 306 | key?: (value: T) => U, |