87 lines
2.0 KiB
JavaScript
87 lines
2.0 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;
|
||
|
||
/**
|
||
* Check if a value is a JS object.
|
||
*
|
||
* @param value Value to check.
|
||
* @return True iff. `value` is a JS object.
|
||
*/
|
||
const isObject = value => value !== null && typeof value === 'object';
|
||
|
||
exports.isObject = isObject;
|
||
|
||
/**
|
||
* Check if two arrays are equal in a shallow manner.
|
||
*
|
||
* @param array1 First array.
|
||
* @param array2 Second array.
|
||
* @return True iff. the two arrays are equal.
|
||
*/
|
||
const arraysEqual = (array1, array2) => (
|
||
array1.length === array2.length
|
||
&& array1.every((elt1, index) => elt1 === array2[index])
|
||
);
|
||
|
||
exports.arraysEqual = arraysEqual;
|