Skip to content

Instantly share code, notes, and snippets.

@MKRhere
Last active July 2, 2020 14:14
Show Gist options
  • Select an option

  • Save MKRhere/3f7ac9154e0810212db12fd0ff83efaf to your computer and use it in GitHub Desktop.

Select an option

Save MKRhere/3f7ac9154e0810212db12fd0ff83efaf to your computer and use it in GitHub Desktop.
Superior generic middleware composition
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