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:
@@ -1,2 +1,2 @@
|
||||
# tools
|
||||
# toolkit
|
||||
My most frequently used tools in programming
|
||||
|
||||
37
plural/README.md
Normal file
37
plural/README.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# Функция изменения формы слов в зависимости от числительного
|
||||
|
||||
Часто встречается задача вывода правильного окончания слова с предшествующим ему числом.
|
||||
|
||||
Например:
|
||||
|
||||
- 1 депутат
|
||||
- 2–4 депутат**а**
|
||||
- 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
9
plural/php/index.php
Normal 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)]
|
||||
];
|
||||
}
|
||||
8
plural/typescript/index.ts
Normal file
8
plural/typescript/index.ts
Normal 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)]
|
||||
];
|
||||
};
|
||||
Reference in New Issue
Block a user