2019-03-02 22:35:43 +05:30
|
|
|
import { sprintf, s__ } from '~/locale';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Combines each given item into a noun series sentence fragment. It does this
|
|
|
|
* in a way that supports i18n by giving context and punctuation to the locale
|
|
|
|
* functions.
|
|
|
|
*
|
|
|
|
* **Examples:**
|
|
|
|
*
|
|
|
|
* - `["A", "B"] => "A and B"`
|
|
|
|
* - `["A", "B", "C"] => "A, B, and C"`
|
|
|
|
*
|
|
|
|
* **Why only nouns?**
|
|
|
|
*
|
|
|
|
* Some languages need a bit more context to translate other series.
|
|
|
|
*
|
|
|
|
* @param {String[]} items
|
|
|
|
*/
|
2021-03-08 18:12:59 +05:30
|
|
|
export const toNounSeriesText = (items, { onlyCommas = false } = {}) => {
|
2019-03-02 22:35:43 +05:30
|
|
|
if (items.length === 0) {
|
|
|
|
return '';
|
|
|
|
} else if (items.length === 1) {
|
2020-07-28 23:09:34 +05:30
|
|
|
return sprintf(s__(`nounSeries|%{item}`), { item: items[0] }, false);
|
2021-03-08 18:12:59 +05:30
|
|
|
} else if (items.length === 2 && !onlyCommas) {
|
2020-07-28 23:09:34 +05:30
|
|
|
return sprintf(
|
|
|
|
s__('nounSeries|%{firstItem} and %{lastItem}'),
|
|
|
|
{
|
|
|
|
firstItem: items[0],
|
|
|
|
lastItem: items[1],
|
|
|
|
},
|
|
|
|
false,
|
|
|
|
);
|
2019-03-02 22:35:43 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
return items.reduce((item, nextItem, idx) =>
|
2021-03-08 18:12:59 +05:30
|
|
|
idx === items.length - 1 && !onlyCommas
|
2020-07-28 23:09:34 +05:30
|
|
|
? sprintf(s__('nounSeries|%{item}, and %{lastItem}'), { item, lastItem: nextItem }, false)
|
|
|
|
: sprintf(s__('nounSeries|%{item}, %{nextItem}'), { item, nextItem }, false),
|
2019-03-02 22:35:43 +05:30
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default {
|
|
|
|
toNounSeriesText,
|
|
|
|
};
|