tracktracker/back/util.js

61 lines
1.4 KiB
JavaScript

/**
* Choose between singular or plural form based on the number of elements.
*
* @example
* > choosePlural(1, 'example', '.s')
* 'example'
* > choosePlural(4, 'example', '.s')
* 'examples'
* > choosePlural(0, 'radius', 'radii')
* 'radii'
*
* @param count Number of elements.
* @param singular Singular form.
* @param plural Plural form. An initial dot will be replaced by `singular`.
* @return Appropriate form.
*/
const choosePlural = (count, singular, plural) =>
{
if (count === 1)
{
return singular;
}
else
{
return plural.replace(/^\./, singular);
}
};
exports.choosePlural = choosePlural;
/**
* Join elements with the given separator and a special separator for the last
* element.
*
* @example
* > joinSentence(['apple', 'orange', 'banana'], ', ', ' and ')
* 'apple, orange and banana'
* > joinSentence(['apple', 'banana'], ', ', ' and ')
* 'apple and banana'
* > joinSentence(['banana'], ', ', ' and ')
* 'banana'
*
* @param array Sequence of strings to join.
* @param separator Separator for all elements but the last one.
* @param lastSeparator Separator for the last element.
* @return Joined string.
*/
const joinSentence = (array, separator, lastSeparator) =>
{
if (array.length <= 2)
{
return array.join(lastSeparator);
}
return array.slice(0, -1).join(separator)
+ lastSeparator
+ array[array.length - 1];
};
exports.joinSentence = joinSentence;