« get me outta code hell

withFlattenedList.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/withFlattenedList.js
blob: edfa34038a0c4fbb7d7fb271cf95c1bab50c9a48 (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
// Flattens an array with one level of nested arrays, providing as dependencies
// both the flattened array as well as the original starting indices of each
// successive source array.
//
// See also:
//  - withUnflattenedList
//
// More list utilities:
//  - excludeFromList
//  - fillMissingListItems
//  - withFilteredList, withMappedList, withSortedList
//  - withPropertyFromList, withPropertiesFromList
//

import {input, templateCompositeFrom} from '#composite';

export default templateCompositeFrom({
  annotation: `withFlattenedList`,

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

  outputs: ['#flattenedList', '#flattenedIndices'],

  steps: () => [
    {
      dependencies: [input('list')],
      compute(continuation, {
        [input('list')]: sourceList,
      }) {
        const flattenedList = sourceList.flat();
        const indices = [];
        let lastEndIndex = 0;
        for (const {length} of sourceList) {
          indices.push(lastEndIndex);
          lastEndIndex += length;
        }

        return continuation({
          ['#flattenedList']: flattenedList,
          ['#flattenedIndices']: indices,
        });
      },
    },
  ],
});