/
index.test.js
103 lines (78 loc) · 2.11 KB
/
index.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
test('BST example in readme.md', () => {
const { BST } = require('./index')
const bst = new BST()
bst.insert(2)
bst.insert(1)
const node = bst.search(1)
bst.delete(1)
expect(node).toEqual({ data: 1, left: null, right: null })
expect(bst.root.left).toBe(null)
})
test('Stack example in readme.md', () => {
const { Stack } = require('./index')
const stack = new Stack()
stack.push(1)
stack.push(2)
const data = stack.pop()
const top = stack.peek()
expect(data).toEqual(2)
expect(top).toEqual(1)
})
test('Queue example in readme.md', () => {
const { Queue } = require('./index')
const queue = new Queue()
queue.enqueue(1)
queue.enqueue(2)
const data = queue.dequeue()
const top = queue.peek()
expect(data).toEqual(1)
expect(top).toEqual(2)
})
test('Heap example in readme.md', () => {
const { Heap } = require('.')
const minHeap = new Heap()
minHeap.push(5)
minHeap.push(2)
let data = minHeap.peek() // 2
expect(data).toEqual(2)
const maxHeap = new Heap((a, b) => b - a)
maxHeap.push(4)
maxHeap.push(10)
data = maxHeap.peek() // 10
expect(data).toEqual(10)
})
it('should construct an empty graph', () => {
const { Graph } = require('.')
expect(new Graph()).toBeDefined()
})
test('disjoint-set example', () => {
const { DisjointSet } = require('./index')
const ds = new DisjointSet()
ds.union('a', 'b')
ds.union('b', 'c')
ds.union('d', 'c')
expect(ds.find('d')).toBe('a')
expect(ds.isConnected('a', 'd')).toBeTruthy()
})
test('LRU Cache example', () => {
const { LRUCache } = require('./index')
const lru = new LRUCache(2)
lru.put(1, 1)
lru.put(2, 2)
lru.get(1) // 1
lru.put(3, 3)
lru.get(2) // -1
lru.put(4, 4)
lru.get(1) // -1
lru.get(3) // 3
lru.get(4) // 4
})
test('hash-set example', () => {
const { HashSet } = require('./index')
const set = new HashSet()
set.add(1)
set.add(2)
expect(set.has(1)).toBeTruthy() // true
expect(set.has(2)).toBeTruthy()
expect(set.has(3)).toBeFalsy()
})