Succession
Succession is a tool for creating dynamic function chains. It is similar to lodash
's flow
or ramda
's pipe
with one important exception, namely that you can force functions to run
at the very start or very end of the chain no matter where the handler is added.
Usage
; const plusTwo = n + 2;const timesTwo = n * 2;const divideTwo = n / 2; const calculate = // ((((10 + 2) * 2) / 2) + 2) = 14console; // 14
Nesting
Nesting also works as expected
// ...const calculate = console; // 14
Force functions to the start or end
Here is the important part: You can then force a handler to the end of the chain from the sub chain.
// ...const addUnits = ` seconds`; const innerChain = ; const calculate = console; // "14 seconds"
Or ensure a handler starts the chain
const calculate = console; // 14
So why would you want to do this?
Here is an example of using succession to configure an express server.
;;; const initApp = app || ; const serveStaticFiles = { app; return app;} const launchServer = { app; return app;} const expressChain = ; ;
Now it is possible for another module to take this chain and add its own express configuration dynamically without having any dependency on the module providing the webserver.
; ;; ;
API
chain(...handlers): Chain
Create a new chain
; const c = ; console; // 2
addLink(handler, order): Chain
Register a handler as a link at a point in the chain given by order
. order is an integer beginning at 1
.
1
will be the first item and 2
will be the second. 0
will leave the order as is.
Negative integers will position items at the end of the list. ie. -1
will push an item to the end. -2
will be second from the end. The method returns the new chain. Note the old chain will not be mutated!
; let calls = ; ; console; // ['a', 'b'] calls = ; ; console; // ['b', 'a']
first(handler): Chain
The same as calling addLink with an order of 1
.
; ;
last(handler): Chain
The same as calling addLink with an order of -1
.
; ;