mirror of
https://github.com/nodejs/node.git
synced 2024-11-21 10:59:27 +00:00
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:
parent
17b9925393
commit
4f84a3d200
44
benchmark/error/format-list.js
Normal file
44
benchmark/error/format-list.js
Normal 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);
|
||||
}
|
@ -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 = {
|
||||
|
@ -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));
|
||||
|
Loading…
Reference in New Issue
Block a user