diff --git a/.changeset/clear-impalas-stare.md b/.changeset/clear-impalas-stare.md new file mode 100644 index 0000000..5217f16 --- /dev/null +++ b/.changeset/clear-impalas-stare.md @@ -0,0 +1,5 @@ +--- +'@electric-sql/d2mini': patch +--- + +make aggregates explicitly optional on a groupBy diff --git a/packages/d2mini/src/operators/groupBy.ts b/packages/d2mini/src/operators/groupBy.ts index b36bbbe..8904106 100644 --- a/packages/d2mini/src/operators/groupBy.ts +++ b/packages/d2mini/src/operators/groupBy.ts @@ -40,7 +40,7 @@ export function groupBy< T, K extends GroupKey, A extends Record>, ->(keyExtractor: (data: T) => K, aggregates: A) { +>(keyExtractor: (data: T) => K, aggregates: A = {} as A) { type ResultType = K & AggregatesReturnType const basicAggregates = Object.fromEntries( diff --git a/packages/d2mini/tests/operators/groupBy.test.ts b/packages/d2mini/tests/operators/groupBy.test.ts index d342ee9..c147620 100644 --- a/packages/d2mini/tests/operators/groupBy.test.ts +++ b/packages/d2mini/tests/operators/groupBy.test.ts @@ -15,6 +15,62 @@ import { output } from '../../src/operators/index.js' describe('Operators', () => { describe('GroupBy operation', () => { + test('with no aggregate', () => { + const graph = new D2() + const input = graph.newInput<{ + category: string + amount: number + }>() + let latestMessage: any = null + + input.pipe( + groupBy((data) => ({ category: data.category })), + output((message) => { + latestMessage = message + }), + ) + + graph.finalize() + + // Initial data + input.sendData( + new MultiSet([ + [{ category: 'A', amount: 10 }, 1], + [{ category: 'A', amount: 20 }, 1], + [{ category: 'B', amount: 30 }, 1], + ]), + ) + graph.run() + + // Verify we have the latest message + expect(latestMessage).not.toBeNull() + + const result = latestMessage.getInner() + + const expectedResult = [ + [ + [ + `{"category":"A"}`, + { + category: 'A', + }, + ], + 1, + ], + [ + [ + `{"category":"B"}`, + { + category: 'B', + }, + ], + 1, + ], + ] + + expect(result).toEqual(expectedResult) + }) + test('with single sum aggregate', () => { const graph = new D2() const input = graph.newInput<{