« get me outta code hell

withUnflattenedList.js « data « composite « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/composite/data/withUnflattenedList.js
blob: 820d628aa4730874ffde81b4e84af264c7d0fc4c (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
// After mapping the contents of a flattened array in-place (being careful to
// retain the original indices by replacing unmatched results with null instead
// of filtering them out), this function allows for recombining them. It will
// filter out null and undefined items by default (pass {filter: false} to
// disable this).
//
// See also:
//  - withFlattenedList
//

import {input, templateCompositeFrom} from '#composite';
import {isWholeNumber, validateArrayItems} from '#validators';

export default templateCompositeFrom({
  annotation: `withUnflattenedList`,

  inputs: {
    list: input({
      type: 'array',
      defaultDependency: '#flattenedList',
    }),

    indices: input({
      validate: validateArrayItems(isWholeNumber),
      defaultDependency: '#flattenedIndices',
    }),

    filter: input({
      type: 'boolean',
      defaultValue: true,
    }),
  },

  outputs: ['#unflattenedList'],

  steps: () => [
    {
      dependencies: [input('list'), input('indices'), input('filter')],
      compute(continuation, {
        [input('list')]: list,
        [input('indices')]: indices,
        [input('filter')]: filter,
      }) {
        const unflattenedList = [];

        for (let i = 0; i < indices.length; i++) {
          const startIndex = indices[i];
          const endIndex =
            (i === indices.length - 1
              ? list.length
              : indices[i + 1]);

          const values = list.slice(startIndex, endIndex);
          unflattenedList.push(
            (filter
              ? values.filter(value => value !== null && value !== undefined)
              : values));
        }

        return continuation({
          ['#unflattenedList']: unflattenedList,
        });
      },
    },
  ],
});