Skip to content

Instantly share code, notes, and snippets.

@yejinjian
Forked from darrenscerri/Middleware.js
Created January 13, 2017 04:40
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 yejinjian/bd845c56ca0afbe8d88b01e7f825b62d to your computer and use it in GitHub Desktop.
Save yejinjian/bd845c56ca0afbe8d88b01e7f825b62d 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.call(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