Skip to content

Instantly share code, notes, and snippets.

@realmyst
Created October 4, 2011 19:34
Show Gist options
  • Save realmyst/1262561 to your computer and use it in GitHub Desktop.
Save realmyst/1262561 to your computer and use it in GitHub Desktop.
Склонение числительных в javascript
function declOfNum(number, titles) {
cases = [2, 0, 1, 1, 1, 2];
return titles[ (number%100>4 && number%100<20)? 2 : cases[(number%10<5)?number%10:5] ];
}
use:
declOfNum(count, ['найдена', 'найдено', 'найдены']);
@Viiprogrammer
Copy link

JSDoc + Using new ES features + can return number with declined string

/**
 * Declines depending on the number
 * @param {number} number
 * @param {string[]} titles Strings for decline
 * @param {boolean} [full=false] If true - returns number + string
 * @return {string}
 */
export function declOfNum (number, titles, full = false) {
  const cases = [2, 0, 1, 1, 1, 2]

  const result = titles[(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]]
  return full ? `${number} ${result}` : result
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment