diff --git a/benchmark/error/format-list.js b/benchmark/error/format-list.js new file mode 100644 index 00000000000000..0f57cd9c7cd8e3 --- /dev/null +++ b/benchmark/error/format-list.js @@ -0,0 +1,29 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + n: [1e7], +}, { + flags: ['--expose-internals'], +}); + +const lists = [ + [], + ['a'], + ['a', 'b'], + ['a', 'b', 'c'], + ]; + +function main({ n }) { + const { + formatList + } = require('internal/errors'); + + bench.start(); + for (let i = 0; i < n; ++i) { + for (let j = 0; j < lists.length; ++j) + formatList(lists[j]); + } + bench.end(n); +} diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 28c241f6fedda9..3889e329e531da 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -901,8 +901,13 @@ function determineSpecificType(value) { * @returns {string} */ function formatList(array, type = 'and') { - return array.length < 3 ? ArrayPrototypeJoin(array, ` ${type} `) : - `${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`; + switch (array.length) { + case 0: return ''; + case 1: return array[0]; + case 2: return `${array[0]} ${type} ${array[1]}`; + default: + return `${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`; + } } module.exports = {