summaryrefslogtreecommitdiff
path: root/ui/lib/iterator.js
blob: 1d6a7407d219e5177fdfac9b792f295019f344ab (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
export function* map(xs, fn) {
  for (const x of xs) {
    yield fn(x);
  }
}

export function reduce(xs, fn, initial) {
  let value = initial;
  for (const x of xs) {
    value = fn(value, x);
  }
  return value;
}

export function* chunkBy(xs, keyFn, coalesceFn) {
  let chunk;
  let key;
  for (const x of xs) {
    const newKey = keyFn(x);

    if (key === undefined) {
      chunk = [x];
    } else if (coalesceFn(key, newKey)) {
      chunk.push(x);
    } else {
      yield { key, chunk };

      chunk = [x];
    }
    key = newKey;
  }
  if (chunk !== undefined) {
    yield { key, chunk };
  }
}