Skip to content

Instantly share code, notes, and snippets.

@brybrophy
Created September 30, 2018 22:40
Show Gist options
  • Save brybrophy/ef57301fffd771f1b10d216631f6e826 to your computer and use it in GitHub Desktop.
Save brybrophy/ef57301fffd771f1b10d216631f6e826 to your computer and use it in GitHub Desktop.
A demonstration of how to use JavaScript closures to create a logged function. The inner function creates a closure containing a function that is passed into the outer function. Each time the inner function is called, it logs that name, arguments, and UTC time that the function in the closure was called.
function createLoggedFunction(fn) {
function loggedFunction(...args) {
const nowUtc = new Date().getTime();
console.log('----Start----');
console.log(`Function ${fn.name} was called with ${args} at ${nowUtc}`);
console.log('-----End-----');
return fn(...args);
};
return loggedFunction;
};
function add(a, b) {
return a + b;
};
const logAdd = createLoggedFunction(add);
const sum = logAdd(100, 300);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment