forked from reactjs/ko.react.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoCommaSeparatedList.js
More file actions
40 lines (32 loc) · 881 Bytes
/
Copy pathtoCommaSeparatedList.js
File metadata and controls
40 lines (32 loc) · 881 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* @emails react-core
* @flow
*/
import React from 'react';
import type {Node} from 'react';
const addString = (list: Array<Node>, string: string) =>
list.push(<span key={`${list.length}-${string}`}>{string}</span>);
const toCommaSeparatedList = (
array: Array<any>,
renderCallback: Function,
): Array<any> => {
if (array.length <= 1) {
return array.map(renderCallback);
}
const list = [];
array.forEach((item, index) => {
if (index === array.length - 1) {
addString(list, array.length === 2 ? ' and ' : ', and ');
list.push(renderCallback(item, index));
} else if (index > 0) {
addString(list, ', ');
list.push(renderCallback(item, index));
} else {
list.push(renderCallback(item, index));
}
});
return list;
};
export default toCommaSeparatedList;