once() and memoize() both took one of Marco’s functions and gave back a new one that did a little extra around it. Now Marco has a different problem. One team’s total came out wrong last week, and he wants to see every call to his scoring functions without editing each of them. He also wants a mistyped score, such as 70 instead of 7, caught before it reaches a total.
In this lesson, you’ll name the pattern behind once() and memoize(), then use it to write two wrappers you can put around any scoring function. You’ll also trace what happens when one wrapper sits inside another.
Log Every Call Without Editing the Function
Marco could add console.log() lines to each scoring function and delete them again once he finds the bug. But that’s an edit to every function, and every edit is a chance to break one. A wrapper adds the logging from outside instead and leaves the function itself alone.
A function that takes a function as an argument or returns one is called a higher-order function. You’ve used them since you first passed a callback to .map(), and once() and memoize() are higher-order functions too. A wrapper is the kind that takes a function and returns a new function that calls it, with extra work before or after.
Here’s a wrapper called withLogging() applied to two of Marco’s functions that take different numbers of arguments. scoreRound() adds a round’s bonus to its number of correct answers, and doublePoints() doubles the points for the round a team picked as its joker:
logging.js
function scoreRound(correct, bonus) {
return correct + bonus;
}
function doublePoints(points) {
return points * 2;
}
function withLogging(fn, label) {
return (...args) => {
console.log(`${label} called with`, args);
const result = fn(...args);
console.log(`${label} returned`, result);
return result;
};
}
const loggedScore = withLogging(scoreRound, "scoreRound");
const loggedDouble = withLogging(doublePoints, "double");
console.log(`Joker round: ${loggedDouble(loggedScore(7, 2))}`);
The label is a setting, like the ones you handed to factories earlier, so each log line says which function it’s about. Run the file, and each call reports what it got and what it gave back: