Skip to content

Commit

Permalink
errors: improve formatList in errors.js
Browse files Browse the repository at this point in the history
PR-URL: #49642
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: LiviaMedeiros <livia@cirno.name>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
  • Loading branch information
Uzlopak committed Sep 29, 2023
1 parent 17b9925 commit 4f84a3d
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 3 deletions.
44 changes: 44 additions & 0 deletions benchmark/error/format-list.js
Original file line number Diff line number Diff line change
@@ -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);
}
10 changes: 8 additions & 2 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
2 changes: 1 addition & 1 deletion test/parallel/test-error-format-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down

0 comments on commit 4f84a3d

Please sign in to comment.