Created
May 29, 2020 10:17
-
-
Save Ivannnnn/cc698b67371d41fc3f6cfabeb8ed48cc to your computer and use it in GitHub Desktop.
This file contains 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
const blockOne = (funcName) => { | |
if (funcName === 'one') { | |
return false | |
} | |
} | |
const emitEvent = (funcName) => { | |
console.log('[event] ' + funcName) | |
} | |
const methods = withMiddleware([blockOne, emitEvent], { | |
one: () => console.log('one'), | |
two: () => console.log('two'), | |
}) | |
methods.one() | |
methods.two() | |
/* console.log | |
[event] two | |
two | |
*/ |
This file contains 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
const withMiddleware = (middleware, methods) => { | |
return new Proxy(methods, { | |
get: (_, methodName) => (...args) => { | |
if (!methods[methodName]) | |
throw new Error(`Method "${methodName}" does not exist!`) | |
middleware.every((mid) => mid(methodName, ...args) !== false) && | |
methods[methodName](...args) | |
}, | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment