Skip to content

Commit e66991e

Browse files
Uzlopaktargos
authored andcommitted
errors: improve formatList in errors.js
PR-URL: #49642 Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: LiviaMedeiros <livia@cirno.name> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
1 parent 55485ff commit e66991e

File tree

3 files changed

+53
-3
lines changed

3 files changed

+53
-3
lines changed

benchmark/error/format-list.js

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
5+
const bench = common.createBenchmark(main, {
6+
n: [1e7],
7+
input: [
8+
'',
9+
'a',
10+
'a,b',
11+
'a,b,c',
12+
'a,b,c,d',
13+
],
14+
type: [
15+
'undefined',
16+
'and',
17+
'or',
18+
],
19+
}, {
20+
flags: ['--expose-internals'],
21+
});
22+
23+
function main({ n, input, type }) {
24+
const {
25+
formatList,
26+
} = require('internal/errors');
27+
28+
const list = input.split(',');
29+
30+
if (type === 'undefined') {
31+
bench.start();
32+
for (let i = 0; i < n; ++i) {
33+
formatList(list);
34+
}
35+
bench.end(n);
36+
return;
37+
}
38+
39+
bench.start();
40+
for (let i = 0; i < n; ++i) {
41+
formatList(list, type);
42+
}
43+
bench.end(n);
44+
}

lib/internal/errors.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -967,8 +967,14 @@ function determineSpecificType(value) {
967967
* @returns {string}
968968
*/
969969
function formatList(array, type = 'and') {
970-
return array.length < 3 ? ArrayPrototypeJoin(array, ` ${type} `) :
971-
`${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`;
970+
switch (array.length) {
971+
case 0: return '';
972+
case 1: return `${array[0]}`;
973+
case 2: return `${array[0]} ${type} ${array[1]}`;
974+
case 3: return `${array[0]}, ${array[1]}, ${type} ${array[2]}`;
975+
default:
976+
return `${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`;
977+
}
972978
}
973979

974980
module.exports = {

test/parallel/test-error-format-list.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ if (!common.hasIntl) common.skip('missing Intl');
1111
const and = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
1212
const or = new Intl.ListFormat('en', { style: 'long', type: 'disjunction' });
1313

14-
const input = ['apple', 'banana', 'orange'];
14+
const input = ['apple', 'banana', 'orange', 'pear'];
1515
for (let i = 0; i < input.length; i++) {
1616
const slicedInput = input.slice(0, i);
1717
strictEqual(formatList(slicedInput), and.format(slicedInput));

0 commit comments

Comments
 (0)