export const getAgeString = (age: number): string => {
if (age < 0) return "Age cannot be negative";
const lastDigit = age % 10;
const isTeen = Math.floor(age / 10) % 10 === 1;
if (isTeen) {
return ${age} лет
;
}
switch (lastDigit) {
case 1:
return `${age} год`;
case 2:
case 3:
case 4:
return `${age} года`;
default:
return `${age} лет`;
}
};
The getAgeString
function takes an age as a number and returns a string with the correct grammatical form of the age in Russian.
How does it work?
- Check for a negative age: If a negative age is passed, the function returns the message “Age cannot be negative.”
- Determine the last digit: The last digit of the age is calculated using the modulo operation with 10.
- Check for “teen” numbers: If the age is in the teens (e.g., 11, 12, 13), it returns a string ending with “лет.”
- Choose the correct suffix:
- If the last digit is 1 (but not 11), it returns a string with “год.”
- If the last digit is 2, 3, or 4 (but not 12, 13, 14), it returns a string with “года.”
- In all other cases, it returns a string with “лет.”
Usage example
console.log(getAgeString(21)); // "21 год"
console.log(getAgeString(22)); // "22 года"
console.log(getAgeString(25)); // "25 лет"
console.log(getAgeString(11)); // "11 лет"
This function is convenient for displaying age in user interfaces of React Native applications, providing correct declension in Russian.