Skip to content

Instantly share code, notes, and snippets.

@joelburton
Created May 21, 2020 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelburton/d9b735fbf8bc80c5508e836bfab1b94f to your computer and use it in GitHub Desktop.
Save joelburton/d9b735fbf8bc80c5508e836bfab1b94f to your computer and use it in GitHub Desktop.
/** A "decorator" -- a function that:
* - takes a function as its arg
* - returns a "wrapped version" of that function
*
* In this case: the wrapped version runs the real function,
* but keeps track of how long it took to run.
*/
function timeit(fn) {
function wrapper(...args) {
const startTime = Date.now();
const result = fn(...args);
const timeInMsec = Date.now() - startTime;
console.debug(fn.name, `(${timeInMsec} ms)`, args, result);
return result;
}
return wrapper;
}
/** An example of a function we'd like to profile: to make it slow, give
it a big `n` and a tiny `chance` */
let slowishThing = function (n, chance) {
for (let i = 0; i < n; i++) {
if (Math.random() < chance) return true;
}
return false;
};
/** A "wrapped" version of our function: we'll just reassign it to the same
* name --- now when you call this function, it will run timeit wrapped
* function, which ultimately calls the real slowishThing */
slowishThing = timeit(slowishThing);
console.log(slowishThing(10000000, 0.000000001));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment