Skip to content

Commit bf2f007

Browse files
committed
remove the sortBy config option, infer the sorting by presence of the _orderByIndex param
1 parent 1e6c0db commit bf2f007

File tree

3 files changed

+13
-12
lines changed

3 files changed

+13
-12
lines changed

packages/optimistic/src/collection.ts

+13-3
Original file line numberDiff line numberDiff line change
@@ -262,9 +262,19 @@ export class Collection<T extends object = Record<string, unknown>> {
262262
// Create a derived array from the map to avoid recalculating it
263263
this.derivedArray = new Derived({
264264
fn: ({ currDepVals: [stateMap] }) => {
265-
const array = Array.from(stateMap.values())
266-
if (config.sortBy) {
267-
array.sort(config.sortBy)
265+
// Collections returned by a query that has an orderBy are annotated
266+
// with the _orderByIndex field.
267+
// This is used to sort the array when it's derived.
268+
const array: Array<T & { _orderByIndex?: number }> = Array.from(
269+
stateMap.values()
270+
)
271+
if (array[0] && `_orderByIndex` in array[0]) {
272+
;(array as Array<T & { _orderByIndex: number }>).sort((a, b) => {
273+
if (a._orderByIndex === b._orderByIndex) {
274+
return 0
275+
}
276+
return a._orderByIndex < b._orderByIndex ? -1 : 1
277+
})
268278
}
269279
return array
270280
},

packages/optimistic/src/query/compiled-query.ts

-8
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ export class CompiledQuery<TResults extends object = Record<string, unknown>> {
2929
constructor(queryBuilder: QueryBuilder<Context<Schema>>) {
3030
const query = queryBuilder._query
3131
const collections = query.collections
32-
const hasOrderBy = !!query.orderBy
3332

3433
if (!collections) {
3534
throw new Error(`No collections provided`)
@@ -104,13 +103,6 @@ export class CompiledQuery<TResults extends object = Record<string, unknown>> {
104103
sync: {
105104
sync,
106105
},
107-
sortBy: hasOrderBy
108-
? (a, b) => {
109-
const aIndex = (a as { _orderByIndex: number })[`_orderByIndex`]
110-
const bIndex = (b as { _orderByIndex: number })[`_orderByIndex`]
111-
return aIndex - bIndex
112-
}
113-
: undefined,
114106
})
115107
}
116108

packages/optimistic/src/types.ts

-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,6 @@ export interface CollectionConfig<T extends object = Record<string, unknown>> {
118118
id: string
119119
sync: SyncConfig<T>
120120
schema?: StandardSchema<T>
121-
sortBy?: (a: T, b: T) => number
122121
}
123122

124123
export type ChangesPayload<T extends object = Record<string, unknown>> = Array<

0 commit comments

Comments
 (0)