All files / app/assets/javascripts/lib/utils grammar.js

100% Statements 9/9
100% Branches 14/14
100% Functions 2/2
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 41 42 43 44 45 46 47                                    45x 43x 1x   42x 5x   37x 2x                   35x 159x                  
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
 */
export const toNounSeriesText = (items, { onlyCommas = false } = {}) => {
  if (items.length === 0) {
    return '';
  }
  if (items.length === 1) {
    return sprintf(s__(`nounSeries|%{item}`), { item: items[0] }, false);
  }
  if (items.length === 2 && !onlyCommas) {
    return sprintf(
      s__('nounSeries|%{firstItem} and %{lastItem}'),
      {
        firstItem: items[0],
        lastItem: items[1],
      },
      false,
    );
  }
 
  return items.reduce((item, nextItem, idx) =>
    idx === items.length - 1 && !onlyCommas
      ? sprintf(s__('nounSeries|%{item}, and %{lastItem}'), { item, lastItem: nextItem }, false)
      : sprintf(s__('nounSeries|%{item}, %{nextItem}'), { item, nextItem }, false),
  );
};
 
export default {
  toNounSeriesText,
};