Skip to content

Commit 27e8b92

Browse files
committed
errors: improve formatList in errors.js
1 parent c19b2a7 commit 27e8b92

File tree

3 files changed

+53
-3
lines changed

3 files changed

+53
-3
lines changed

benchmark/error/format-list.js

Lines changed: 44 additions & 0 deletions
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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -902,8 +902,14 @@ function determineSpecificType(value) {
902902
* @returns {string}
903903
*/
904904
function formatList(array, type = 'and') {
905-
return array.length < 3 ? ArrayPrototypeJoin(array, ` ${type} `) :
906-
`${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`;
905+
switch (array.length) {
906+
case 0: return '';
907+
case 1: return `${array[0]}`;
908+
case 2: return `${array[0]} ${type} ${array[1]}`;
909+
case 3: return `${array[0]}, ${array[1]}, ${type} ${array[2]}`;
910+
default:
911+
return `${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`;
912+
}
907913
}
908914

909915
module.exports = {

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

Lines changed: 1 addition & 1 deletion
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)