summaryrefslogtreecommitdiff
path: root/ui/lib/iterator.test.js
blob: 4c5535862d443ff36aa9869db68d9c307bfb3aa6 (plain)
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
import * as iter from './iterator.js';
import { beforeEach, expect, test, describe, it, vi } from 'vitest';

describe('map', async () => {
  it('applies the mapping function to each item', async () => {
    const seq = Iterator.from([1, 2, 3, 5, 8]);
    const mapped = iter.map(seq, (x) => 2 * x);
    expect(Array.from(mapped)).toStrictEqual([2, 4, 6, 10, 16]);
  });
});

describe('reduce', async () => {
  it('accumulates results and returns them', async () => {
    const seq = Iterator.from([1, 2, 3, 4]);
    const reduced = iter.reduce(seq, (sum, x) => sum + x, 0);

    // Good ol' triangle numbers.
    expect(reduced).toStrictEqual(10);
  });
});

describe('chunkBy', async () => {
  describe('with trivial operand functions', async () => {
    it('yields nothing for an empty input', async () => {
      const chunks = iter.chunkBy(
        [],
        (val) => val,
        (last, next) => last === next
      );

      expect(Array.from(chunks)).toStrictEqual([]);
    });

    it('yields one chunk input for a singleton input', async () => {
      const chunks = iter.chunkBy(
        [37],
        (val) => val,
        (last, next) => last === next
      );

      expect(Array.from(chunks)).toStrictEqual([{ key: 37, chunk: [37] }]);
    });

    it('yields chunks of successive inputs', async () => {
      const chunks = iter.chunkBy(
        [37, 37, 28, 37],
        (val) => val,
        (last, next) => last === next
      );

      expect(Array.from(chunks)).toStrictEqual([
        { key: 37, chunk: [37, 37] },
        { key: 28, chunk: [28] },
        {
          key: 37,
          chunk: [37]
        }
      ]);
    });
  });

  describe('with a complex key function', async () => {
    it('returns the key with each chunk', async () => {
      const chunks = iter.chunkBy(
        [37, 37, 28, 37],
        (val) => val >> 1,
        (last, next) => last === next
      );

      expect(Array.from(chunks)).toStrictEqual([
        { key: 18, chunk: [37, 37] },
        { key: 14, chunk: [28] },
        { key: 18, chunk: [37] }
      ]);
    });
  });

  describe('with a complex coalesce function', async () => {
    it('continues the chunk when specified', async () => {
      const chunks = iter.chunkBy(
        [36, 37, 28, 29, 30, 38],
        (val) => val,
        (last, next) => last + 1 === next
      );

      expect(Array.from(chunks)).toStrictEqual([
        { key: 37, chunk: [36, 37] },
        { key: 30, chunk: [28, 29, 30] },
        { key: 38, chunk: [38] }
      ]);
    });
  });
});