« get me outta code hell

withPropertyFromList.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/withPropertyFromList.js
blob: a2c66d77f3b8ca8976e95f889157ff7ed064a5db (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
// Gets a property from each of a list of objects (in a dependency) and
// provides the results.
//
// This doesn't alter any list indices, so positions which were null in the
// original list are kept null here. Objects which don't have the specified
// property are retained in-place as null.
//
// See also:
//  - withPropertiesFromList
//  - withPropertyFromObject
//
// More list utilities:
//  - excludeFromList
//  - fillMissingListItems
//  - withFilteredList, withMappedList, withSortedList
//  - withFlattenedList, withUnflattenedList
//

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

function getOutputName({list, property, prefix}) {
  if (!property) return `#values`;
  if (prefix) return `${prefix}.${property}`;
  if (list) return `${list}.${property}`;
  return `#list.${property}`;
}

export default templateCompositeFrom({
  annotation: `withPropertyFromList`,

  inputs: {
    list: input({type: 'array'}),
    property: input({type: 'string'}),
    prefix: input.staticValue({type: 'string', defaultValue: null}),
  },

  outputs: ({
    [input.staticDependency('list')]: list,
    [input.staticValue('property')]: property,
    [input.staticValue('prefix')]: prefix,
  }) =>
    [getOutputName({list, property, prefix})],

  steps: () => [
    {
      dependencies: [input('list'), input('property')],
      compute: (continuation, {
        [input('list')]: list,
        [input('property')]: property,
      }) => continuation({
        ['#values']:
          list.map(item => item[property] ?? null),
      }),
    },

    {
      dependencies: [
        input.staticDependency('list'),
        input.staticValue('property'),
        input.staticValue('prefix'),
      ],

      compute: (continuation, {
        [input.staticDependency('list')]: list,
        [input.staticValue('property')]: property,
        [input.staticValue('prefix')]: prefix,
      }) => continuation({
        ['#outputName']:
          getOutputName({list, property, prefix}),
      }),
    },

    {
      dependencies: ['#values', '#outputName'],
      compute: (continuation, {
        ['#values']: values,
        ['#outputName']: outputName,
      }) =>
        continuation.raiseOutput({[outputName]: values}),
    },
  ],
});