Skip to content

Instantly share code, notes, and snippets.

@robdodson
Created August 31, 2012 20:38
Show Gist options
  • Select an option

  • Save robdodson/3558664 to your computer and use it in GitHub Desktop.

Select an option

Save robdodson/3558664 to your computer and use it in GitHub Desktop.
wrapper
/**
* 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