Last active
July 2, 2020 14:14
-
-
Save MKRhere/3f7ac9154e0810212db12fd0ff83efaf to your computer and use it in GitHub Desktop.
Superior generic middleware composition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); | |
| const listeners = {}; | |
| const on = (ev, ...handlers) => { | |
| if (!listeners[ev]) listeners[ev] = []; | |
| listeners[ev].push(compose(...handlers)(x => x)); | |
| }; | |
| const emit = (ev, ctx) => { | |
| const list = listeners[ev]; | |
| if (list) list.forEach(listener => listener(ctx)); | |
| }; | |
| on( | |
| "hello", | |
| next => ctx => { | |
| ctx.a = true; | |
| next(ctx); | |
| }, | |
| next => ctx => { | |
| ctx.b = true; | |
| next(ctx); | |
| }, | |
| next => ctx => { | |
| ctx.respond({ success: ctx.a && ctx.b }); | |
| }, | |
| ); | |
| emit("hello", { respond: x => console.log(x) }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment