Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

map.test.ts

108 lines2.1 KB

1import { describe, expect, test } from 'vitest'
2import { D2 } from '../../src/d2.js'
3import { MultiSet } from '../../src/multiset.js'
4import { map, output } from '../../src/operators/index.js'
5​
6describe(`Operators`, () => {
7 describe(`Map operation`, () => {
8 test(`basic map operation`, () => {
9 const graph = new D2()
10 const input = graph.newInput<number>()
11 const messages: Array<MultiSet<number>> = []
12​
13 input.pipe(
14 map((x) => x + 5),
15 output((message) => {
16 messages.push(message)
17 }),
18 )
19​
20 graph.finalize()
21​
22 input.sendData(
23 new MultiSet([
24 [1, 1],
25 [2, 1],
26 [3, 1],
27 ]),
28 )
29​
30 graph.run()
31​
32 expect(messages).toEqual([
33 new MultiSet([
34 [6, 1],
35 [7, 1],
36 [8, 1],
37 ]),
38 ])
39 })
40​
41 test(`map with multiple transformations`, () => {
42 const graph = new D2()
43 const input = graph.newInput<number>()
44 const messages: Array<MultiSet<number>> = []
45​
46 input.pipe(
47 map((x) => x * 2),
48 map((x) => x + 1),
49 output((message) => {
50 messages.push(message)
51 }),
52 )
53​
54 graph.finalize()
55​
56 input.sendData(
57 new MultiSet([
58 [1, 1],
59 [2, 1],
60 [3, 1],
61 ]),
62 )
63​
64 graph.run()
65​
66 expect(messages).toEqual([
67 new MultiSet([
68 [3, 1],
69 [5, 1],
70 [7, 1],
71 ]),
72 ])
73 })
74​
75 test(`map with negative multiplicities`, () => {
76 const graph = new D2()
77 const input = graph.newInput<number>()
78 const messages: Array<MultiSet<number>> = []
79​
80 input.pipe(
81 map((x) => x + 1),
82 output((message) => {
83 messages.push(message)
84 }),
85 )
86​
87 graph.finalize()
88​
89 input.sendData(
90 new MultiSet([
91 [1, -1],
92 [2, -2],
93 [3, 1],
94 ]),
95 )
96​
97 graph.run()
98​
99 expect(messages).toEqual([
100 new MultiSet([
101 [2, -1],
102 [3, -2],
103 [4, 1],
104 ]),
105 ])
106 })
107 })
108})