tracktracker/src/util.js

87 lines
2.0 KiB
JavaScript
Raw Normal View History

2020-01-13 11:20:35 +00:00
/**
* Choose between singular or plural form based on the number of elements.
2020-01-13 11:20:35 +00:00
*
* @example
* > choosePlural(1, 'example', '.s')
* 'example'
* > choosePlural(4, 'example', '.s')
* 'examples'
* > choosePlural(0, 'radius', 'radii')
* 'radii'
2020-01-13 11:20:35 +00:00
*
* @param count Number of elements.
* @param singular Singular form.
* @param plural Plural form. An initial dot will be replaced by `singular`.
* @return Appropriate form.
2020-01-13 11:20:35 +00:00
*/
const choosePlural = (count, singular, plural) =>
2020-01-13 11:20:35 +00:00
{
if (count === 1)
2020-01-13 11:20:35 +00:00
{
return singular;
}
else
2020-01-13 11:20:35 +00:00
{
return plural.replace(/^\./, singular);
}
};
exports.choosePlural = choosePlural;
2020-01-13 11:20:35 +00:00
/**
* 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);
}
2020-01-13 11:20:35 +00:00
return (
array.slice(0, -1).join(separator)
+ lastSeparator
+ array[array.length - 1]
);
2020-01-13 11:20:35 +00:00
};
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;