Skip to content

Instantly share code, notes, and snippets.

@sylvainleris
Forked from darrenscerri/Middleware.js
Last active March 16, 2023 12:42
Show Gist options
  • Save sylvainleris/6a051f2a9e7420b32b6db7d8d47b968b to your computer and use it in GitHub Desktop.
Save sylvainleris/6a051f2a9e7420b32b6db7d8d47b968b 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
});
@swapnilaryan
Copy link

Hi,
Great job in simplifying the implementation of darrenscerri/Middleware.js
Can you simplify more the "use" method and "next()" functionality as I am new to ES6 and JS world ?

@coreybutler
Copy link

Modifying the array prototype seems unnecessary, with potential consequences. This version accomplishes the same thing.

const last = a => a[a.length - 1]
const reduce = a => a.slice(0, -1)

class Middleware {
  use (method) {
    this.go = ((stack) => (...args) => stack(...reduce(args), () => {
      const next = last(args)
      method.apply(this, [...reduce(args), next.bind.apply(next, [null, ...reduce(args)])])
    }))(this.go)
  }

  go (...args) {
    last(args).apply(this, reduce(args))
  }
}

@shennan
Copy link

shennan commented May 16, 2020

In order to chain a lá

middleware
  .use(fn)
  .use(fn)

you could return this at the end of the use method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment