Created
August 31, 2012 20:38
-
-
Save robdodson/3558664 to your computer and use it in GitHub Desktop.
wrapper
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
| /** | |
| * Wraps a `Function` with another `Function`. This allows | |
| * the wrapper function to intercept and manipulate the | |
| * return value of the orginal function. | |
| * @param {Function} fn The function to wrap | |
| * @param {Function} wrapper The wrapper function | |
| * @return {Function} Return the wrapped function | |
| */ | |
| function wrap(fn, wrapper) { | |
| return function() { | |
| var args = slice.apply(arguments); | |
| return wrapper.apply(this, [fn].concat(args)); | |
| }; | |
| } | |
| // Usage | |
| var wrappedFn = wrap(sum, function() { | |
| var args = sp.slice.apply(arguments); | |
| // First argument is the wrapped function | |
| var originalFn = args.shift(); | |
| return originalFn.apply(this, args) * 2; | |
| }); | |
| expect(wrappedFn(1, 2, 3, 4)).toEqual(20); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment