Skip to content

Commit

Permalink
add timed functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Qix- committed Aug 9, 2017
1 parent 8e91e44 commit d817675
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/debug.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,37 @@ function createDebug(namespace) {
return section;
};

debug.time = function () {
var args = [].slice.call(arguments);
if (args.length < 2) {
throw new Error('debug.time() takes at least a debug string and a function');
}

var fn = args.pop();
if (typeof fn !== 'function') {
throw new Error('the last argument to debug.time() must be a function');
}

var isPromise = false;
var section = debug.begin.apply(debug, args);
try {
var result = fn();

if (typeof Promise === 'function' && result instanceof Promise) { // eslint-disable-line no-undef
isPromise = true;
result.then(function () {
section.end();
});
}

return result;
} finally {
if (!isPromise) {
section.end();
}
}
};

// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
Expand Down
12 changes: 12 additions & 0 deletions test/debug_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,18 @@ describe('debug', function () {

expect(log.log).to.have.been.calledThrice;
});

it('times a critical function', function () {
log.log = sinon.spy();

var result = log.time('a critical function', function () {
log('hello from inside');
return 1234;
});

expect(result).to.equal(1234);
expect(log.log).to.have.been.calledThrice;
});
});
});
});

0 comments on commit d817675

Please sign in to comment.