Class: What

What()

The What class provides a functional abstraction layer for fluent, composable logic.

Integrates seamlessly with Each and AsyncEach for declarative pipelines. Each instance is:

  • Callable like a function
  • Fluent via chainable methods

Shared semantic API (9 core methods): if(), sthen(), else(), which(), when(), match(), each(), self(), and what().

Constructor

new What()

Example
const doublePlusOne = What.as(x => x * 2)
  .if(x => x > 0)
  .sthen(x => x + 1);

doublePlusOne(5);       // => 11
doublePlusOne.what(5);  // => 11

Methods

each(f) → {What}

Dynamic version: cartesian product of twoextends results for a given call.

Applies a function or What instance f to each result produced by this What and flattens the final Each of iterables into an Each.

Parameters:
Name Type Description
f function | What

Function or What to apply to each result of this What.

Returns:

A new What that flattens and iterates all results produced by f.

Type
What

else(f, matcheropt) → {What}

Attach a fallback to handle missing results or matching errors.

This dynamic version of else extends the primary function with recovery logic:

  • If the primary function returns undefined, the fallback f is invoked.
  • If the primary function throws an error, the error is tested against the optional matcher.
    • If it matches, the fallback f is invoked instead.
    • If it does not match, the error is re-thrown.
  • When the fallback is invoked due to an error, the error object is appended as the last argument to f.

Error matching is delegated to Errors.matches, which supports:

  • number: compares against err.statusCode
  • string: compares against error class name, or substring match for thrown strings
  • RegExp: tested against the error message or thrown string
  • Function: custom predicate (err) => boolean

Constants (non-functions) are automatically lifted into functions returning that constant.

Parameters:
Name Type Attributes Description
f function | What | *

Fallback to use if the primary returns undefined or a matching error is thrown. If f is a constant it is converted to a What returning it.

matcher string | number | RegExp | function <optional>

Optional matcher to restrict which errors trigger the fallback. If omitted, all errors are caught.

Returns:

A new What instance with fallback behavior applied.

Type
What

if(popt, erroropt) → {What}

Conditional execution: keep only inputs passing a predicate.

Wraps this What so that it executes only if the predicate returns true. If the predicate returns false, returns undefined by default. Optionally, an error can be provided to be thrown.

Parameters:
Name Type Attributes Default Description
p function <optional>
item => item !== undefined

Predicate (…args) => boolean applied to the input(s).

error Error <optional>

Optional error to throw if predicate fails.

Returns:

A new What filtered by the predicate.

Type
What

match(…ff) → {What}

Zip multiple What instances.

Parameters:
Name Type Attributes Description
ff What | function <repeatable>
Returns:
Type
What

self(arg0opt, arg1opt, baseDelayopt, factoropt, maxDelayopt) → {AsyncWhat|What}

Dynamically adapts this What instance for different use cases depending on the arguments.

The behavior depends on the arguments passed, supporting multiple overload modes:

  1. Path-expanding mode (no arguments):

    • self()
    • Converts this What: item -> items to a What: path -> paths by expanding path.last through the original function.
  2. Context-mapping / nominal mode (string or string[] as first argument):

    • self(name) → extracts ctx[name] and passes it as input.
    • self(nameIn, nameOut) → maps ctx[nameIn] to input and stores result in ctx[nameOut].
    • self([name1, name2, ...]) → extracts multiple properties from context.
    • self([name1, name2, ...], nameOut) → stores result in ctx[nameOut].
  3. Argument-binding mode (two numeric arguments):

    • self(index, value)
    • Injects value into the argument list at position index.
  4. Timeout mode (single numeric argument):

    • self(timeoutMs)
    • Promotes this What to an AsyncWhat that rejects if the computation does not complete within timeoutMs milliseconds.
  5. Retry mode (numeric first argument with ≥3 args):

    • self(nAttempts, baseDelay, factor, maxDelay)
    • Promotes this What to an AsyncWhat that retries execution up to nAttempts with exponential backoff. The resulting AsyncWhat exposes a .stopped property to cancel the retries.
Parameters:
Name Type Attributes Default Description
arg0 number | string | Array.<string> <optional>

Numeric index, retry attempts, timeout in ms, or property name(s)

arg1 number | string <optional>

Value to inject (argument-binding), output property name (nominal mode), or retry attempts (retry mode)

baseDelay number <optional>
100

Base delay in ms for retry mode

factor number <optional>
1

Exponential backoff factor for retry mode

maxDelay number <optional>
Infinity

Maximum delay for retry mode

Returns:

A new instance wrapping the adapted behavior: - What for path-expanding, context-mapping, argument-binding - AsyncWhat for timeout or retry mode

Type
AsyncWhat | What

sthen(…f) → {What}

Map values through a function.

Parameters:
Name Type Attributes Description
f function <repeatable>

Functions to apply

Returns:
Type
What

when(predicate, emitter, event, timeoutMsopt, startopt) → {AsyncWhat}

Asynchronous conditional in event-driven mode.

Promotes the current What (this) into an AsyncWhat that wraps the underlying logic and executes conditionally based on the occurrence of a specified event and a predicate.

Behavior:

  • start = true: the underlying AsyncWhat is executed only when the predicate evaluates truthy upon the event.
  • start = false: the underlying AsyncWhat is immediately invoked (so it can run and be stopped), and will be stopped when the predicate evaluates truthy upon the event.

If no matching event occurs within timeoutMs, the returned AsyncWhat rejects with a TimeoutError.

The returned AsyncWhat proxies the .stopped property of the underlying AsyncWhat, allowing external control over cyclic or self-driven executions.

Example: infinite cyclic execution with start/stop triggers

const cyclic = doSomething.self(Infinity, 100, 1);

const bounded = cyclic .when( isStart, // predicate identifying start condition emitter, // event source event, // event name to listen for undefined, // optional timeout true // start cyclic execution when event occurs ) .when( isStop, // predicate identifying stop condition emitter, event, undefined, false // stop cyclic execution when event occurs );

bounded();

Parameters:
Name Type Attributes Default Description
predicate function

Predicate (…eventArgs, emitter) => boolean | Promise<boolean) to evaluate event arguments

emitter EventEmitter | EventTarget

Event source

event string

Event name to listen for

timeoutMs number <optional>

Optional timeout in milliseconds

start boolean <optional>
true

If true, executes the underlying AsyncWhat when predicate matches; if false, immediately invokes the underlying AsyncWhat and stops it when predicate matches

Throws:

If no matching event occurs within the specified timeout

Type
TimeoutError
Returns:

An AsyncWhat that resolves with the result of the underlying function (if starting) or undefined (if stopping)

Type
AsyncWhat

which(popt, erroropt) → {What}

Conditional output filter: keeps only results that satisfy the predicate.

Executes this What and evaluates the predicate on the result. If the predicate returns false, returns undefined by default. Optionally, it can throw a provided error.

Parameters:
Name Type Attributes Default Description
p function <optional>
item => item !== undefined

Predicate (result, …args) => boolean applied to the result.

error Error <optional>

Error to throw if predicate fails.

Returns:

A new What filtered by the predicate.

Type
What

(static) as(f) → {What}

Wrap a value, function, or What instance as a What.

Parameters:
Name Type Description
f *

Value, function, or What instance

Returns:
Type
What

(static) each(…ff) → {What}

Static version: generates a search space of Paths across multiple Functions.

Parameters:
Name Type Attributes Description
ff What | function <repeatable>

Functions or What instances

Returns:

A What returning all incremental path dispositions

Type
What

(static) of(…items) → {What}

Creates a What instance that returns a fixed value when called with an exact sequence of arguments.

Essentially defines a single mapping:

(arg1, arg2, ..., argN) → value

If the input arguments exactly match the defined sequence (deep equality check via Each.equal), the stored value is returned; otherwise undefined.

Example

const f = What.of(1, 2, "answer");
console.log(f(1, 2));    // "answer"
console.log(f(1));       // undefined
console.log(f(2, 1));    // undefined
Parameters:
Name Type Attributes Description
items * <repeatable>

Argument sequence followed by the return value. The last element in items is treated as the value, while the preceding elements are the argument pattern to match.

Returns:

A What instance mapping the specified arguments to the given value.

Type
What

(static) retype(f, instance) → {What}

Attach the prototype of instance to function f.

Parameters:
Name Type Description
f function

Function to retype

instance Object

Reference instance whose prototype to adopt

Returns:
Type
What