Skip to content

Commit 73ffb34

Browse files
committed
perf: improve formatList in errors.js
1 parent 4e01842 commit 73ffb34

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

benchmark/error/format-list.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
5+
const bench = common.createBenchmark(main, {
6+
n: [1e7],
7+
}, {
8+
flags: ['--expose-internals'],
9+
});
10+
11+
const lists = [
12+
[],
13+
['a'],
14+
['a', 'b'],
15+
['a', 'b', 'c'],
16+
];
17+
18+
function main({ n }) {
19+
const {
20+
formatList
21+
} = require('internal/errors');
22+
23+
bench.start();
24+
for (let i = 0; i < n; ++i) {
25+
for (let j = 0; j < lists.length; ++j)
26+
formatList(lists[j]);
27+
}
28+
bench.end(n);
29+
}

lib/internal/errors.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -901,8 +901,13 @@ function determineSpecificType(value) {
901901
* @returns {string}
902902
*/
903903
function formatList(array, type = 'and') {
904-
return array.length < 3 ? ArrayPrototypeJoin(array, ` ${type} `) :
905-
`${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`;
904+
switch (array.length) {
905+
case 0: return '';
906+
case 1: return array[0];
907+
case 2: return `${array[0]} ${type} ${array[1]}`;
908+
default:
909+
return `${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`;
910+
}
906911
}
907912

908913
module.exports = {

0 commit comments

Comments
 (0)