Last active
August 29, 2015 14:01
-
-
Save phillipj/89d0c7696efeca4cbd9d to your computer and use it in GitHub Desktop.
JavaScript functional wrapping experiment
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
// 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