Skip to content

Commit

Permalink
errors: 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 f001dd7
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 = [
[],

Check failure on line 12 in benchmark/error/format-list.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Expected indentation of 2 spaces but found 4
['a'],

Check failure on line 13 in benchmark/error/format-list.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Expected indentation of 2 spaces but found 4
['a', 'b'],

Check failure on line 14 in benchmark/error/format-list.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Expected indentation of 2 spaces but found 4
['a', 'b', 'c'],

Check failure on line 15 in benchmark/error/format-list.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Expected indentation of 2 spaces but found 4
];

Check failure on line 16 in benchmark/error/format-list.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Expected indentation of 0 spaces but found 2

function main({ n }) {
const {
formatList

Check failure on line 20 in benchmark/error/format-list.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Missing trailing comma
} = require('internal/errors');

bench.start();
for (let i = 0; i < n; ++i) {
for (let j = 0; j < lists.length; ++j)
formatList(lists[j]);

Check failure on line 26 in benchmark/error/format-list.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Expected indentation of 6 spaces but found 4
}
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 f001dd7

Please sign in to comment.