A tiny cascading state machine.
installation:
npm i --save @jdw/cascade
usage:
import cascade from '@jdw/cascade';
const increment = x => x++;
const square = x => Math.pow(x, x);
// apply state to functions and sequentially
// calculate a result
cascade(100)
.chain(square)
.chain(increment)
.read(); // 10001
This initialization method takes an initial state and returns a Cascade
object.
This method takes function fn
invoking it with the machines state as an
argument and then mutating state to the result.
example:
return cascade(1)
.chain(x => x + 1) // internal state set to: 2
.chain(x => x * x) // internal state set to: 4
.read() // return internal state: 4
As above however with the optional recovery method cb
supplied. cb
is invoked
in case something went wrong with the error, state, and fn
supplied as its
arguments.
example:
const process = state => throw new Error();
const recover = (err, state, fn) => state + 10;
return cascade(90)
.chain(process, recover) // errors on process() invoking recover().
.read(); // outputs: 100
Returns the current state of the machine.
example:
return cascade(true)
.read(); // true