Skip to content

Commit 1c910df

Browse files
committed
feat(internal): formatList
Signed-off-by: Lexus Drumgold <[email protected]>
1 parent f744782 commit 1c910df

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @file Unit Tests - formatList
3+
* @module create-error-node/internal/tests/unit/formatList
4+
*/
5+
6+
import testSubject from '../format-list'
7+
8+
describe('unit:internal/formatList', () => {
9+
it('should return list string', () => {
10+
// Arrange
11+
const cases: [...Parameters<typeof testSubject>, string][] = [
12+
[['json'], undefined, 'json'],
13+
[['data', 'file'], undefined, 'data and file'],
14+
[['boolean', 'number', 'string'], 'or', 'boolean, number, or string']
15+
]
16+
17+
// Act + Expect
18+
cases.forEach(([arr, transition, expected]) => {
19+
expect(testSubject(arr, transition)).to.equal(expected)
20+
})
21+
})
22+
})

src/internal/format-list.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @file Internal - formatList
3+
* @module errnode/internal/formatList
4+
* @see https://github.com/nodejs/node/blob/0f69ec4dd74d446765639274728466baf5f13cdd/lib/internal/errors.js#L905-L908
5+
*/
6+
7+
/**
8+
* Creates a list string in the form `'A and B'` or `'A, B, ..., and Z`.
9+
*
10+
* @example
11+
* formatList(['json'])
12+
* // 'json'
13+
* @example
14+
* formatList(['data', 'file'])
15+
* // 'data and file'
16+
* @example
17+
* formatList(['boolean', 'number', 'string'], 'or')
18+
* // 'boolean, number, or string'
19+
*
20+
* @param {string[]} arr - List elements
21+
* @param {string?} [transition='and'] - Word to be inserted before last element
22+
* @return {string} List string
23+
*/
24+
function formatList(arr: string[], transition: string = 'and'): string {
25+
return arr.length < 3
26+
? arr.join(` ${transition} `)
27+
: `${arr.slice(0, -1).join(', ')}, ${transition} ${arr[arr.length - 1]}`
28+
}
29+
30+
export default formatList

0 commit comments

Comments
 (0)