Skip to content

Instantly share code, notes, and snippets.

@phillipj
Last active August 29, 2015 14:01
Show Gist options
  • Save phillipj/89d0c7696efeca4cbd9d to your computer and use it in GitHub Desktop.
Save phillipj/89d0c7696efeca4cbd9d to your computer and use it in GitHub Desktop.
JavaScript functional wrapping experiment
// doing some functional wrapping as a proof-of-concept for extensibility
var multiply = (function createMultiplier(invokeFn) {
var invoke = invokeFn || function (a, b) {
return a * b;
};
return {
wrap: function (fn) {
return createMultiplier(fn(invoke));
},
invoke: invoke
};
})();
var logit = function (innerFn) {
return function () {
var startMillis = +new Date();
var result = innerFn.apply(null, arguments);
var endMillis = +new Date();
console.log('Multiplication into %s took %s ms', result, (endMillis - startMillis));
return result;
};
};
var timesTwo = function (innerFn) {
return function () {
return innerFn.apply(null, arguments) * 2;
};
};
// one might visualize the callchain as logit(timesTwo(originalMultiplyFn(2, 3)))
console.log(multiply.wrap(timesTwo).wrap(logit).invoke(2, 3));
// $ node fn-wrapping.js
// Multiplication into 12 took 1 ms
// 12
// for inspiration:
// - https://github.com/briancavalier/aop-s2gx-2013/blob/master/src/aop-simple.js
// - http://blakeembrey.com/articles/wrapping-javascript-functions/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment