1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 02:44:45 +00:00

Plural php + ts

This commit is contained in:
2022-08-13 23:59:23 +07:00
committed by GitHub
parent e7fc5a37d5
commit b3893a5e3e
4 changed files with 55 additions and 1 deletions

View File

@@ -1,2 +1,2 @@
# tools
# toolkit
My most frequently used tools in programming

37
plural/README.md Normal file
View File

@@ -0,0 +1,37 @@
# Функция изменения формы слов в зависимости от числительного
Часто встречается задача вывода правильного окончания слова с предшествующим ему числом.
Например:
- 1 депутат
- 24 депутат**а**
- 0, 5-9 или 10 депутат**ов**
## Примеры исользования
### Typescript
```typescript
import { plural } from 'plural';
const totalOrders = 2;
const words = ['заказ', 'заказа', 'заказов'];
const result = `${totalOrders} ${plural(totalOrders, words)}`;
console.log(result); // 2 заказа
```
### PHP
```php
include 'plural.php';
$totalOrders = 2;
$words = ['заказ', 'заказа', 'заказов'];
$result = "{$totalOrders} {plural($totalOrders, $words)}";
echo result; // 2 заказа
```

9
plural/php/index.php Normal file
View File

@@ -0,0 +1,9 @@
<?php
function plural(int $count, array $words)
{
$cases = [2, 0, 1, 1, 1, 2];
return $words[
$count % 100 > 4 && $count % 100 < 20 ? 2 : $cases[min($count % 10, 5)]
];
}

View File

@@ -0,0 +1,8 @@
export type WordForms = [string, string, string];
export const plural = (count: number, words: WordForms): string => {
const cases = [2, 0, 1, 1, 1, 2];
return words[
count % 100 > 4 && count % 100 < 20 ? 2 : cases[Math.min(count % 10, 5)]
];
};