Skip to content

Instantly share code, notes, and snippets.

@krogla
Forked from sylvainleris/MiddlewareES6.js
Created April 29, 2020 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krogla/a67a4d442d86ae261e844ab2a2309d98 to your computer and use it in GitHub Desktop.
Save krogla/a67a4d442d86ae261e844ab2a2309d98 to your computer and use it in GitHub Desktop.
A very minimal Javascript (ES5 & ES6) Middleware Pattern Implementation
class Middleware {
constructor() {
// Array prototype last
if (!Array.prototype.last) {
Array.prototype.last = function() {
return this[this.length - 1];
}
}
// Array prototype reduceOneRight
if (!Array.prototype.reduceOneRight) {
Array.prototype.reduceOneRight = function() {
return this.slice(0, -1);
}
}
}
use(fn) {
this.go = ((stack) => (...args) => stack(...args.reduceOneRight(), () => {
let _next = args.last();
fn.apply(this, [...args.reduceOneRight(), _next.bind.apply(_next, [null, ...args.reduceOneRight()])]);
}))(this.go);
}
go(...args) {
let _next = args.last();
_next.apply(this, args.reduceOneRight());
}
}
var middleware = new Middleware();
middleware.use((hook, next) => {
setTimeout(() => {
hook.value++;
next();
}, 10);
});
middleware.use((hook, next) => {
setTimeout(() => {
hook.value++;
next();
}, 10);
});
var start = new Date();
middleware.go({value:1}, (hook) => {
console.log(hook.value); // 3
console.log(new Date() - start); // around 20
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment