Created
September 20, 2013 15:50
-
-
Save lastguest/6639622 to your computer and use it in GitHub Desktop.
Wrap a function with a middleware decorator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Generate a middleware | |
function middleware(mw){ | |
return function(fn){ | |
fn = (typeof fn == "function") ? fn : window[fn]; | |
return function(){ | |
var args = arguments || []; | |
if(false !== mw.apply(this,args)) fn.apply(this,args); | |
}; | |
}; | |
} | |
// Example middleware, only accept knowed people | |
var mustBeAquaintance = middleware(function(name){ | |
// check if user is logged in here | |
var iKnowYou = ['Jack','Lisa'].indexOf(name)>=0; | |
if( ! iKnowYou ){ | |
console.log(name + "? I don't know you, go away."); | |
return false; | |
} | |
}); | |
// The naive function | |
var letMeIn = function(name){ | |
console.log("Hello "+name+", how are you?"); | |
}; | |
// Naive version | |
letMeIn('Jack'); | |
letMeIn('Frank'); | |
letMeIn('Lisa'); | |
// Apply middleware | |
letMeIn = mustBeAquaintance(letMeIn); | |
console.log("\nParanoic Mode: on\n"); | |
// Paranoic version | |
letMeIn('Jack'); | |
letMeIn('Frank'); | |
letMeIn('Lisa'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment