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

multiset.test.ts

110 lines2.9 KB

1import { beforeEach, describe, expect, it } from 'vitest'
2import { MultiSet } from '../src/multiset.js'
3​
4describe(`MultiSet`, () => {
5 describe(`basic operations`, () => {
6 let a: MultiSet<[string, string | Array<string>]>
7 let b: MultiSet<[string, string | Array<string>]>
8​
9 beforeEach(() => {
10 a = new MultiSet<[string, string | Array<string>]>([
11 [[`apple`, `$5`], 2],
12 [[`banana`, `$2`], 1],
13 ])
14 b = new MultiSet<[string, string | Array<string>]>([
15 [[`apple`, `$3`], 1],
16 [[`apple`, [`granny smith`, `$2`]], 1],
17 [[`kiwi`, `$2`], 1],
18 ])
19 })
20​
21 it(`should concatenate two multisets`, () => {
22 const concat = a.concat(b)
23 expect(concat.getInner()).toEqual([
24 [[`apple`, `$5`], 2],
25 [[`banana`, `$2`], 1],
26 [[`apple`, `$3`], 1],
27 [[`apple`, [`granny smith`, `$2`]], 1],
28 [[`kiwi`, `$2`], 1],
29 ])
30 })
31​
32 it(`should filter elements`, () => {
33 const filtered = a.filter((data) => data[0] !== `apple`)
34 expect(filtered.getInner()).toEqual([[[`banana`, `$2`], 1]])
35 })
36​
37 it(`should map elements`, () => {
38 const mapped = a.map((data) => [data[1], data[0]])
39 expect(mapped.getInner()).toEqual([
40 [[`$5`, `apple`], 2],
41 [[`$2`, `banana`], 1],
42 ])
43 })
44 })
45​
46 it(`should handle negative multiplicities correctly`, () => {
47 const a = new MultiSet([[1, 1]])
48 const b = new MultiSet([[1, -1]])
49 const result = a.concat(b).consolidate()
50 expect(result.getInner()).toHaveLength(0)
51 })
52​
53 it(`should consolidate simple string values`, () => {
54 // Create a multiset with duplicate string values that need consolidation
55 const stringSet = new MultiSet<string>([
56 [`a`, 1],
57 [`a`, 2],
58 [`b`, 3],
59 [`b`, 1],
60 [`c`, 1],
61 ])
62​
63 const consolidated = stringSet.consolidate()
64​
65 // After consolidation, duplicates should be combined
66 expect(consolidated.getInner()).toEqual([
67 [`a`, 3],
68 [`b`, 4],
69 [`c`, 1],
70 ])
71 })
72​
73 it(`should consolidate simple number values`, () => {
74 // Create a multiset with duplicate number values that need consolidation
75 const numberSet = new MultiSet<number>([
76 [1, 2],
77 [1, 3],
78 [2, 1],
79 [2, 2],
80 [3, 1],
81 ])
82​
83 const consolidated = numberSet.consolidate()
84​
85 // After consolidation, duplicates should be combined
86 expect(consolidated.getInner()).toEqual([
87 [1, 5],
88 [2, 3],
89 [3, 1],
90 ])
91 })
92​
93 it(`should consolidate mixed string and number values`, () => {
94 // Create a multiset with mixed types that will require JSON stringification
95 const mixedSet = new MultiSet<string | number>([
96 [1, 2],
97 [`1`, 3],
98 [1, 1],
99 [`1`, 2],
100 ])
101​
102 const consolidated = mixedSet.consolidate()
103​
104 // After consolidation, the number 1 and string '1' should remain separate
105 expect(consolidated.getInner()).toEqual([
106 [1, 3],
107 [`1`, 5],
108 ])
109 })
110})