File size: 1,736 Bytes
90cbf22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { MinHeap } from './minheap';

describe('MinHeap', () => {
  const compareNumbers = (a: number, b: number): boolean => a > b;

  test('should initialize an empty heap', () => {
    const heap = MinHeap(compareNumbers);
    expect(heap.length()).toBe(0);
    expect(heap.peek()).toBeUndefined();
  });

  test('should insert values correctly and maintain the min property', () => {
    const heap = MinHeap(compareNumbers);
    heap.push(3);
    heap.push(1);
    heap.push(4);
    heap.push(2);

    expect(heap.peek()).toBe(1);
    expect(heap.length()).toBe(4);
  });

  test('should pop values correctly and maintain the min property', () => {
    const heap = MinHeap(compareNumbers);
    heap.push(3);
    heap.push(1);
    heap.push(4);
    heap.push(2);

    expect(heap.pop()).toBe(1);
    expect(heap.length()).toBe(3);
    expect(heap.peek()).toBe(2);

    expect(heap.pop()).toBe(2);
    expect(heap.length()).toBe(2);
    expect(heap.peek()).toBe(3);
  });

  test('should handle popping from an empty heap', () => {
    const heap = MinHeap(compareNumbers);
    expect(heap.pop()).toBeUndefined();
    expect(heap.length()).toBe(0);
    expect(heap.peek()).toBeUndefined();
  });

  test('should handle peeking from an empty heap', () => {
    const heap = MinHeap(compareNumbers);
    expect(heap.peek()).toBeUndefined();
  });

  test('should handle custom comparison functions', () => {
    const compareStringsByLength = (a: string, b: string): boolean => a.length > b.length;
    const heap = MinHeap(compareStringsByLength);
    heap.push('apple');
    heap.push('banana');
    heap.push('cherry');

    expect(heap.peek()).toBe('apple');
    heap.push('kiwi');
    expect(heap.peek()).toBe('kiwi');
  });
});