Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

errors: improve formatList in errors.js #49642

Merged
merged 1 commit into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -902,8 +902,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