errors: improve formatList in errors.js

PR-URL: https://github.com/nodejs/node/pull/49642
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: LiviaMedeiros <livia@cirno.name>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Aras Abbasi 2023-09-29 13:04:38 +02:00 committed by GitHub
parent 17b9925393
commit 4f84a3d200
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 53 additions and 3 deletions

View File

@ -0,0 +1,44 @@
'use strict';
const common = require('../common.js');
const bench = common.createBenchmark(main, {
n: [1e7],
input: [
'',
'a',
'a,b',
'a,b,c',
'a,b,c,d',
],
type: [
'undefined',
'and',
'or',
],
}, {
flags: ['--expose-internals'],
});
function main({ n, input, type }) {
const {
formatList,
} = require('internal/errors');
const list = input.split(',');
if (type === 'undefined') {
bench.start();
for (let i = 0; i < n; ++i) {
formatList(list);
}
bench.end(n);
return;
}
bench.start();
for (let i = 0; i < n; ++i) {
formatList(list, type);
}
bench.end(n);
}

View File

@ -967,8 +967,14 @@ 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]}`;
case 3: return `${array[0]}, ${array[1]}, ${type} ${array[2]}`;
default:
return `${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`;
}
}
module.exports = {

View File

@ -11,7 +11,7 @@ if (!common.hasIntl) common.skip('missing Intl');
const and = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
const or = new Intl.ListFormat('en', { style: 'long', type: 'disjunction' });
const input = ['apple', 'banana', 'orange'];
const input = ['apple', 'banana', 'orange', 'pear'];
for (let i = 0; i < input.length; i++) {
const slicedInput = input.slice(0, i);
strictEqual(formatList(slicedInput), and.format(slicedInput));