Browse Source

console: coerce label to string in console.time()

Per the console spec, the label in console.time() is a string.
Per the console spec, the default value of label is `'default'`.

PR-URL: https://github.com/nodejs/node/pull/14643
Reviewed-By: Refael Ackermann <refack@gmail.com>
Reviewed-By: Timothy Gu <timothygu99@gmail.com>
Reviewed-By: Khaidi Chu <i@2333.moe>
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
v6
James M Snell 7 years ago
parent
commit
4da8b99a74
  1. 4
      doc/api/console.md
  2. 8
      lib/console.js
  3. 20
      test/parallel/test-console.js

4
doc/api/console.md

@ -321,7 +321,7 @@ See [`util.format()`][] for more information.
<!-- YAML
added: v0.1.104
-->
* `label` {string}
* `label` {string} Defaults to `'default'`.
Starts a timer that can be used to compute the duration of an operation. Timers
are identified by a unique `label`. Use the same `label` when calling
@ -337,7 +337,7 @@ changes:
description: This method no longer supports multiple calls that don’t map
to individual `console.time()` calls; see below for details.
-->
* `label` {string}
* `label` {string} Defaults to `'default'`.
Stops a timer that was previously started by calling [`console.time()`][] and
prints the result to `stdout`:

8
lib/console.js

@ -139,12 +139,16 @@ Console.prototype.dir = function dir(object, options) {
};
Console.prototype.time = function time(label) {
Console.prototype.time = function time(label = 'default') {
// Coerces everything other than Symbol to a string
label = `${label}`;
this._times.set(label, process.hrtime());
};
Console.prototype.timeEnd = function timeEnd(label) {
Console.prototype.timeEnd = function timeEnd(label = 'default') {
// Coerces everything other than Symbol to a string
label = `${label}`;
const time = this._times.get(label);
if (!time) {
process.emitWarning(`No such label '${label}' for console.timeEnd()`);

20
test/parallel/test-console.js

@ -42,6 +42,12 @@ assert.doesNotThrow(function() {
console.timeEnd('label');
});
assert.throws(() => console.time(Symbol('test')),
/^TypeError: Cannot convert a Symbol value to a string$/);
assert.throws(() => console.timeEnd(Symbol('test')),
/^TypeError: Cannot convert a Symbol value to a string$/);
// an Object with a custom .inspect() function
const custom_inspect = { foo: 'bar', inspect: () => 'inspect' };
@ -103,6 +109,20 @@ console.timeEnd('constructor');
console.time('hasOwnProperty');
console.timeEnd('hasOwnProperty');
// verify that values are coerced to strings
console.time([]);
console.timeEnd([]);
console.time({});
console.timeEnd({});
console.time(null);
console.timeEnd(null);
console.time(undefined);
console.timeEnd('default');
console.time('default');
console.timeEnd();
console.time(NaN);
console.timeEnd(NaN);
assert.strictEqual(strings.length, process.stdout.writeTimes);
assert.strictEqual(errStrings.length, process.stderr.writeTimes);
common.restoreStdout();

Loading…
Cancel
Save