Skip to content

Instantly share code, notes, and snippets.

@emilbayes
Created November 26, 2012 20:40
Show Gist options
  • Save emilbayes/4150481 to your computer and use it in GitHub Desktop.
Save emilbayes/4150481 to your computer and use it in GitHub Desktop.
Middleware Stack
`
Object.isObject = function(_obj) {
var _test = _obj;
return ( typeof _obj !== 'object' || _obj === null ?
false :
(
(function () {
while (!false) {
if ( Object.getPrototypeOf( _test = Object.getPrototypeOf(_test) ) === null) {
break;
}
}
return Object.getPrototypeOf(_obj) === _test;
})()
)
);
}
if(!Array.isArray) {
Array.isArray = function (vArg) {
return Object.prototype.toString.call(vArg) === "[object Array]";
};
}
`
class MiddlewareStack
constructor: ->
@stack = []
use: (fn) ->
if Array.isArray fn
@stack.push fn...
else
@stack[@stack.length] = fn
@
walk: (initial) ->
if not Array.isArray(initial) and not Object.isObject(initial)
throw new Error 'Initial value must be an array or an object'
i = 0
next = () =>
return if i == @stack.length
@stack[i++].call initial, initial, next
next()
initial
plus = (ø, next) -> @.d += 2; next()
minus = (ø, next) -> @.d -= 0.5; next()
times = (ø, next) -> @.d *= 10; next()
s = new MiddlewareStack()
s.use plus
s.use [minus, times]
alert s.walk 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment