Skip to content

Instantly share code, notes, and snippets.

@catalsdevelop
Forked from darrenscerri/Middleware.js
Created May 8, 2018 21:56
Show Gist options
  • Save catalsdevelop/f33c260880a2938057eb279775ab86e5 to your computer and use it in GitHub Desktop.
Save catalsdevelop/f33c260880a2938057eb279775ab86e5 to your computer and use it in GitHub Desktop.
A very minimal Javascript (ES5 & ES6) Middleware Pattern Implementation
var Middleware = function() {};
Middleware.prototype.use = function(fn) {
var self = this;
this.go = (function(stack) {
return function(next) {
stack.call(self, function() {
fn.call(self, next.bind(self));
});
}.bind(this);
})(this.go);
};
Middleware.prototype.go = function(next) {
next();
};
class Middleware {
use(fn) {
this.go = (stack => next => stack(fn.bind(this, next.bind(this))))(this.go);
}
go = next => next();
}
// Inspired by: https://github.com/kolodny/exercises/tree/master/middleware
var middleware = new Middleware();
middleware.use(function(next) {
var self = this;
setTimeout(function() {
self.hook1 = true;
next();
}, 10);
});
middleware.use(function(next) {
var self = this;
setTimeout(function() {
self.hook2 = true;
next();
}, 10);
});
var start = new Date();
middleware.go(function() {
console.log(this.hook1); // true
console.log(this.hook2); // true
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