tracktracker/src/util.js

87 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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 JSobject.
*/
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;