Skip to content

Commit 5c3b834

Browse files
authored
make aggregates explicitly optional on a groupBy (electric-sql#67)
* make aggrigates explicity optional on a groupBy * changeset
1 parent 109861e commit 5c3b834

File tree

3 files changed

+62
-1
lines changed

3 files changed

+62
-1
lines changed

.changeset/clear-impalas-stare.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@electric-sql/d2mini': patch
3+
---
4+
5+
make aggregates explicitly optional on a groupBy

packages/d2mini/src/operators/groupBy.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export function groupBy<
4040
T,
4141
K extends GroupKey,
4242
A extends Record<string, AggregateFunction<T, any, any>>,
43-
>(keyExtractor: (data: T) => K, aggregates: A) {
43+
>(keyExtractor: (data: T) => K, aggregates: A = {} as A) {
4444
type ResultType = K & AggregatesReturnType<T, A>
4545

4646
const basicAggregates = Object.fromEntries(

packages/d2mini/tests/operators/groupBy.test.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,62 @@ import { output } from '../../src/operators/index.js'
1515

1616
describe('Operators', () => {
1717
describe('GroupBy operation', () => {
18+
test('with no aggregate', () => {
19+
const graph = new D2()
20+
const input = graph.newInput<{
21+
category: string
22+
amount: number
23+
}>()
24+
let latestMessage: any = null
25+
26+
input.pipe(
27+
groupBy((data) => ({ category: data.category })),
28+
output((message) => {
29+
latestMessage = message
30+
}),
31+
)
32+
33+
graph.finalize()
34+
35+
// Initial data
36+
input.sendData(
37+
new MultiSet([
38+
[{ category: 'A', amount: 10 }, 1],
39+
[{ category: 'A', amount: 20 }, 1],
40+
[{ category: 'B', amount: 30 }, 1],
41+
]),
42+
)
43+
graph.run()
44+
45+
// Verify we have the latest message
46+
expect(latestMessage).not.toBeNull()
47+
48+
const result = latestMessage.getInner()
49+
50+
const expectedResult = [
51+
[
52+
[
53+
`{"category":"A"}`,
54+
{
55+
category: 'A',
56+
},
57+
],
58+
1,
59+
],
60+
[
61+
[
62+
`{"category":"B"}`,
63+
{
64+
category: 'B',
65+
},
66+
],
67+
1,
68+
],
69+
]
70+
71+
expect(result).toEqual(expectedResult)
72+
})
73+
1874
test('with single sum aggregate', () => {
1975
const graph = new D2()
2076
const input = graph.newInput<{

0 commit comments

Comments
 (0)