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 0f76852
Show file tree
Hide file tree
Showing 2 changed files with 71 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
40 changes: 40 additions & 0 deletions test/debug_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,46 @@ 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;
});

it('should throw if there aren\'t enough arguments', function () {
log.log = sinon.stub();

expect(function () {
log.time();
}).to.throw('debug.time() takes at least a debug string and a function');

expect(function () {
log.time('hello');
}).to.throw('debug.time() takes at least a debug string and a function');

expect(function () {
log.time(function () {});
}).to.throw('debug.time() takes at least a debug string and a function');
});

it('should throw if last argument isn\'t a function', function () {
log.log = sinon.stub();

expect(function () {
log.time('hello', 1234);
}).to.throw('the last argument to debug.time() must be a function');

expect(function () {
log.time('hello', function () {}, 1235);
}).to.throw('the last argument to debug.time() must be a function');
});
});
});
});

0 comments on commit 0f76852

Please sign in to comment.