« get me outta code hell

withResultOfAvailabilityCheck.js « control-flow « composite « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/composite/control-flow/withResultOfAvailabilityCheck.js
blob: a694201422df81fabde115e4d1ea28c93c34d4f7 (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
// Checks the availability of a dependency and provides the result to later
// steps under '#availability' (by default). This is mainly intended for use
// by the more specific utilities, which you should consider using instead.
//
// Customize {mode} to select one of these modes, or default to 'null':
//
// * 'null':  Check that the value isn't null (and not undefined either).
// * 'empty': Check that the value is neither null, undefined, nor an empty
//            array.
// * 'falsy': Check that the value isn't false when treated as a boolean
//            (nor an empty array). Keep in mind this will also be false
//            for values like zero and the empty string!
// * 'index': Check that the value is a number, and is at least zero.
//
// See also:
//  - exitWithoutDependency
//  - exitWithoutUpdateValue
//  - exposeDependencyOrContinue
//  - exposeUpdateValueOrContinue
//  - raiseOutputWithoutDependency
//  - raiseOutputWithoutUpdateValue
//

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

import inputAvailabilityCheckMode from './inputAvailabilityCheckMode.js';

export default templateCompositeFrom({
  annotation: `withResultOfAvailabilityCheck`,

  inputs: {
    from: input({acceptsNull: true}),
    mode: inputAvailabilityCheckMode(),
  },

  outputs: ['#availability'],

  steps: () => [
    {
      dependencies: [input('from'), input('mode')],

      compute: (continuation, {
        [input('from')]: value,
        [input('mode')]: mode,
      }) => {
        let availability;

        switch (mode) {
          case 'null':
            availability = value !== undefined && value !== null;
            break;

          case 'empty':
            availability = value !== undefined && !empty(value);
            break;

          case 'falsy':
            availability = !!value && (!Array.isArray(value) || !empty(value));
            break;

          case 'index':
            availability = typeof value === 'number' && value >= 0;
            break;
        }

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