Skip to content

Commit

Permalink
improve benchmark, optimize for case 3 too.
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak committed Sep 19, 2023
1 parent c93b86b commit bea7335
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
20 changes: 18 additions & 2 deletions benchmark/error/format-list.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,36 @@ const bench = common.createBenchmark(main, {
'a',
'a,b',
'a,b,c',
'a,b,c,d',
],
type: [
'undefined',
'and',
'or',
],
}, {
flags: ['--expose-internals'],
});

function main({ n, input }) {
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);
formatList(list, type);
}
bench.end(n);
}
1 change: 1 addition & 0 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -906,6 +906,7 @@ function formatList(array, type = 'and') {
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]}`;
}
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 bea7335

Please sign in to comment.