Skip to content

Commit b2d79ff

Browse files
authored
Create join_and.ts
1 parent 4bb0b25 commit b2d79ff

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/format/join_and.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
2+
/**
3+
* This function takes an array of elements and returns a new string by concatenating all of the
4+
* elements in this array except of the last element. The last element is concatenated with the
5+
* `and` character string as a prefix.
6+
*
7+
* @example
8+
* ```
9+
* console.log(joinAnd([1, 2, 3]))
10+
* // 1,2 and 3
11+
*
12+
* console.log(joinAnd(['foo', 'bar', 'baz'], ', ', ' but not '))
13+
* // foo, bar but not baz
14+
* ```
15+
* @param elements
16+
* @param [separator=','] A string to separate each pair of adjacent elements of the array
17+
* @param [and=' and '] A string prefix for concatenating the last element
18+
* @returns The new concatenated string
19+
*/
20+
export default function joinAnd(
21+
elements : (string | number)[],
22+
separator : string = ',',
23+
and : string = ' and '
24+
) : string {
25+
if (elements.length === 0) {
26+
return ''
27+
}
28+
if (elements.length === 1) {
29+
return elements[0].toString()
30+
}
31+
32+
return elements.slice(0, -1).join(separator) + and + elements.at(-1)
33+
}

0 commit comments

Comments
 (0)