Created
November 1, 2015 15:17
-
-
Save gmmorris/fd019977c11f04e039fc to your computer and use it in GitHub Desktop.
An example of a composer higher order function for my How to Grok a Higher Order Class article
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
// Our higher order function which logs all returned values to the function properties on an object | |
function attachLogger(objectOrFunction) { | |
if(typeof objectOrFunction === 'function'){ | |
return function() { | |
let ret = objectOrFunction.apply(this, arguments); | |
console.log(ret); | |
return ret; | |
} | |
} | |
for (name in objectOrFunction){ | |
let method = objectOrFunction[name]; | |
if (typeof method === "function"){ | |
objectOrFunction[name] = attachLogger(objectOrFunction[name]); | |
} | |
} | |
return objectOrFunction; | |
} | |
// we have component which fetches a price in pennies | |
const PriceFetcher = { | |
getPriceInPence : function(productId) { | |
// .. fetch price from API | |
} | |
}; | |
const performSomeAction = function() { | |
// ... | |
}; | |
// attach logging functionality | |
PriceFetcher = attachLogger(PriceFetcher); | |
performSomeAction = attachLogger(performSomeAction); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment