Skip to content

Commit

Permalink
perf: improve formatList in errors.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak committed Sep 14, 2023
1 parent 4e01842 commit 73ffb34
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
29 changes: 29 additions & 0 deletions benchmark/error/format-list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict';

const common = require('../common.js');

const bench = common.createBenchmark(main, {
n: [1e7],
}, {
flags: ['--expose-internals'],
});

const lists = [
[],
['a'],
['a', 'b'],
['a', 'b', 'c'],
];

function main({ n }) {
const {
formatList
} = require('internal/errors');

bench.start();
for (let i = 0; i < n; ++i) {
for (let j = 0; j < lists.length; ++j)
formatList(lists[j]);
}
bench.end(n);
}
9 changes: 7 additions & 2 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -901,8 +901,13 @@ 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]}`;
default:
return `${ArrayPrototypeJoin(ArrayPrototypeSlice(array, 0, -1), ', ')}, ${type} ${array[array.length - 1]}`;
}
}

module.exports = {
Expand Down

0 comments on commit 73ffb34

Please sign in to comment.