Skip to content

Commit ea8615a

Browse files
author
Serhii Shramko
committed
docs: update UA readme
1 parent 1ed9eb1 commit ea8615a

File tree

4 files changed

+358
-54
lines changed

4 files changed

+358
-54
lines changed

README.ukrainian.md

Lines changed: 50 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -380,157 +380,153 @@ Read in a different language: [![CN](./assets/flags/CN.png)**CN**](./README.chin
380380

381381
**В іншому випадку:** Уявіть таку ситуацію – ваша функція очікує числовий аргумент "Знижка", який викликаюча сторона забуває передати, потім ваш код перевіряє, чи Знижка!=0 (розмір дозволеної знижки більший ніж нуль), тоді він дозволить користувачу отримати знижку. О боже, яка неприємна помилка. Бачите її?
382382

383-
🔗 [**Читати більше: швидке виявлення помилок**](./sections/errorhandling/failfast.md)
383+
🔗 [**Читати більше: швидке виявлення помилок**](./sections/errorhandling/failfast.ukrainian.md)
384384

385385
<br/><br/>
386386

387-
## ![] 2.12 Always await promises before returning to avoid a partial stacktrace
387+
## ![] 2.12 Завжди очікуйте проміси перед поверненням, щоб уникнути часткового стеку викликів
388388

389-
**TL;DR:** Always do `return await` when returning a promise to benefit full error stacktrace. If a
390-
function returns a promise, that function must be declared as `async` function and explicitly
391-
`await` the promise before returning it
389+
**Коротко:** Завжди використовуйте `return await` при поверненні промісу, щоб отримати повний стек помилок. Якщо функція повертає проміс, ця функція повинна бути оголошена як `async` функція і явно використовувати `await` для промісу перед його поверненням
392390

393-
**Otherwise:** The function that returns a promise without awaiting won't appear in the stacktrace.
394-
Such missing frames would probably complicate the understanding of the flow that leads to the error,
395-
especially if the cause of the abnormal behavior is inside of the missing function
391+
**В іншому випадку:** Функція, яка повертає проміс без очікування, не з'явиться у стеку викликів. Такі відсутні кадри, ймовірно, ускладнять розуміння потоку, що призвів до помилки, особливо якщо причина аномальної поведінки знаходиться всередині відсутньої функції
396392

397-
🔗 [**Read More: returning promises**](./sections/errorhandling/returningpromises.md)
393+
🔗 [**Читати більше: повернення промісу**](./sections/errorhandling/returningpromises.ukrainian.md)
398394

399395
<br/><br/><br/>
400396

401397
<p align="right"><a href="#table-of-contents">⬆ Return to top</a></p>
402398

403399
# `3. Code Style Practices`
404400

405-
## ![] 3.1 Use ESLint
401+
## ![] 3.1 Використовуйте ESLint
406402

407-
**TL;DR:** [ESLint](https://eslint.org) is the de-facto standard for checking possible code errors and fixing code style, not only to identify nitty-gritty spacing issues but also to detect serious code anti-patterns like developers throwing errors without classification. Though ESLint can automatically fix code styles, other tools like [prettier](https://www.npmjs.com/package/prettier) and [beautify](https://www.npmjs.com/package/js-beautify) are more powerful in formatting the fix and work in conjunction with ESLint
403+
**Коротко:** [ESLint](https://eslint.org) є фактичним стандартом для перевірки можливих помилок у коді та виправлення стилю коду. Він допомагає не лише виявити дрібні проблеми зі структурою коду, такі як зайві пробіли, але й серйозні антипатерни коду, наприклад, коли розробники кидають помилки без класифікації. Хоча ESLint може автоматично виправляти стиль коду, інші інструменти, такі як [prettier](https://www.npmjs.com/package/prettier) і [beautify](https://www.npmjs.com/package/js-beautify), більш потужні у форматуванні виправлень і працюють разом з ESLint.
408404

409-
**Otherwise:** Developers will focus on tedious spacing and line-width concerns and time might be wasted overthinking the project's code style
405+
**В іншому випадку:** Розробники зосереджуватимуться на нудних питаннях щодо пробілів та ширини рядків, а час може бути витрачено на надмірне обдумування стилю коду проєкту.
410406

411-
🔗 [**Read More: Using ESLint and Prettier**](./sections/codestylepractices/eslint_prettier.md)
407+
🔗 [**Детальніше: Використання ESLint та Prettier**](./sections/codestylepractices/eslint_prettier.ukrainian.md)
412408

413409
<br/><br/>
414410

415-
## ![] 3.2 Node.js specific plugins
411+
## ![] 3.2 Специфічні плагіни для Node.js
416412

417-
**TL;DR:** On top of ESLint standard rules that cover vanilla JavaScript, add Node.js specific plugins like [eslint-plugin-node](https://www.npmjs.com/package/eslint-plugin-node), [eslint-plugin-mocha](https://www.npmjs.com/package/eslint-plugin-mocha) and [eslint-plugin-node-security](https://www.npmjs.com/package/eslint-plugin-security)
413+
**Коротко:** Окрім стандартних правил ESLint, що охоплюють ванільний JavaScript, додайте специфічні плагіни для Node.js, такі як [eslint-plugin-node](https://www.npmjs.com/package/eslint-plugin-node), [eslint-plugin-mocha](https://www.npmjs.com/package/eslint-plugin-mocha) і [eslint-plugin-node-security](https://www.npmjs.com/package/eslint-plugin-security).
418414

419-
**Otherwise:** Many faulty Node.js code patterns might escape under the radar. For example, developers might require(variableAsPath) files with a variable given as a path which allows attackers to execute any JS script. Node.js linters can detect such patterns and complain early
415+
**Інакше:** Багато проблемних шаблонів коду Node.js можуть залишитися непоміченими. Наприклад, розробники можуть використовувати require(variableAsPath) для підключення файлів з передачею змінної як шляху, що дозволяє зловмисникам виконувати будь-який JS-скрипт. Лінтери Node.js можуть виявляти такі шаблони та попереджати про них заздалегідь.
420416

421417
<br/><br/>
422418

423-
## ![] 3.3 Start a Codeblock's Curly Braces on the Same Line
419+
## ![] 3.3 Відкривайте фігурні дужки коду на тому ж рядку
424420

425-
**TL;DR:** The opening curly braces of a code block should be on the same line as the opening statement
421+
**Коротко:** Відкриваючі фігурні дужки блоку коду повинні бути на тому ж рядку, що й оператор відкриття.
426422

427-
### Code Example
423+
### Приклад коду
428424

429425
```javascript
430-
// Do
426+
// Правильно
431427
function someFunction() {
432-
// code block
428+
// блок коду
433429
}
434430

435-
// Avoid
431+
// Уникайте
436432
function someFunction()
437433
{
438-
// code block
434+
// блок коду
439435
}
440436
```
441437

442-
**Otherwise:** Deferring from this best practice might lead to unexpected results, as seen in the StackOverflow thread below:
438+
**Інакше:** Відхилення від цієї практики може призвести до несподіваних результатів, як показано в обговоренні на StackOverflow нижче:
443439

444-
🔗 [**Read more:** "Why do results vary based on curly brace placement?" (StackOverflow)](https://stackoverflow.com/questions/3641519/why-does-a-results-vary-based-on-curly-brace-placement)
440+
🔗 [**Читати більше:** "Чому результати варіюються залежно від розміщення фігурних дужок?" (StackOverflow)](https://stackoverflow.com/questions/3641519/why-does-a-results-vary-based-on-curly-brace-placement)
445441

446442
<br/><br/>
447443

448-
## ![] 3.4 Separate your statements properly
444+
## ![] 3.4 Правильно розділяйте свої вирази
449445

450-
No matter if you use semicolons or not to separate your statements, knowing the common pitfalls of improper linebreaks or automatic semicolon insertion, will help you to eliminate regular syntax errors.
446+
Незалежно від того, використовуєте ви крапки з комами для розділення виразів чи ні, знання поширених помилок, пов'язаних з неправильними розривами рядків або автоматичною вставкою крапок з комами, допоможе уникнути регулярних синтаксичних помилок.
451447

452-
**TL;DR:** Use ESLint to gain awareness about separation concerns. [Prettier](https://prettier.io/) or [Standardjs](https://standardjs.com/) can automatically resolve these issues.
448+
**Коротко:** Використовуйте ESLint для підвищення обізнаності про проблеми з розділенням виразів. [Prettier](https://prettier.io/) або [Standardjs](https://standardjs.com/) можуть автоматично вирішити ці проблеми.
453449

454-
**Otherwise:** As seen in the previous section, JavaScript's interpreter automatically adds a semicolon at the end of a statement if there isn't one, or considers a statement as not ended where it should, which might lead to some undesired results. You can use assignments and avoid using immediately invoked function expressions to prevent most of the unexpected errors.
450+
**Інакше:** Як було показано в попередньому розділі, інтерпретатор JavaScript автоматично додає крапку з комою в кінці виразу, якщо її немає, або вважає, що вираз не завершено там, де це потрібно, що може призвести до небажаних результатів. Ви можете використовувати присвоєння і уникати безпосередньо викликаних функціональних виразів (IIFE), щоб уникнути більшості несподіваних помилок.
455451

456-
### Code example
452+
### Приклад коду
457453

458454
```javascript
459-
// Do
455+
// Правильно
460456
function doThing() {
461457
// ...
462458
}
463459

464460
doThing()
465461

466-
// Do
462+
// Правильно
467463

468464
const items = [1, 2, 3]
469465
items.forEach(console.log)
470466

471-
// Avoidthrows exception
467+
// Неправильновиникає виняток
472468
const m = new Map()
473469
const a = [1,2,3]
474470
[...m.values()].forEach(console.log)
475471
> [...m.values()].forEach(console.log)
476472
> ^^^
477473
> SyntaxError: Unexpected token ...
478474

479-
// Avoidthrows exception
480-
const count = 2 // it tries to run 2(), but 2 is not a function
475+
// Неправильновиникає виняток
476+
const count = 2 // інтерпретатор намагається виконати 2(), але 2 не є функцією
481477
(function doSomething() {
482-
// do something amazing
478+
// зробити щось чудове
483479
}())
484-
// put a semicolon before the immediate invoked function, after the const definition, save the return value of the anonymous function to a variable or avoid IIFEs altogether
480+
// вставте крапку з комою перед безпосередньо викликаним виразом, після визначення const, збережіть результат анонімної функції у змінну або уникайте IIFE взагалі
485481
```
486482

487-
🔗 [**Read more:** "Semi ESLint rule"](https://eslint.org/docs/rules/semi)
488-
🔗 [**Read more:** "No unexpected multiline ESLint rule"](https://eslint.org/docs/rules/no-unexpected-multiline)
483+
🔗 [**Читати більше:** "Правило ESLint для крапок з комами"](https://eslint.org/docs/rules/semi)
484+
🔗 [**Читати більше:** "Правило ESLint для несподіваних розривів рядків"](https://eslint.org/docs/rules/no-unexpected-multiline)
489485

490486
<br/><br/>
491487

492-
## ![] 3.5 Name your functions
488+
## ![] 3.5 Давайте імена своїм функціям
493489

494-
**TL;DR:** Name all functions, including closures and callbacks. Avoid anonymous functions. This is especially useful when profiling a node app. Naming all functions will allow you to easily understand what you're looking at when checking a memory snapshot
490+
**Коротко:** Давайте імена всім функціям, включно із замиканнями та зворотними викликами. Уникайте анонімних функцій. Це особливо корисно при профілюванні Node.js додатків. Присвоєння імен функціям дозволить вам легко розуміти, що ви переглядаєте під час аналізу знімку пам'яті.
495491

496-
**Otherwise:** Debugging production issues using a core dump (memory snapshot) might become challenging as you notice significant memory consumption from anonymous functions
492+
**Інакше:** Виправлення проблем на продакшені за допомогою core dump (знімка пам'яті) може стати складним завданням, оскільки ви можете помітити значне споживання пам'яті анонімними функціями.
497493

498494
<br/><br/>
499495

500-
## ![] 3.6 Use naming conventions for variables, constants, functions and classes
496+
## ![] 3.6 Використовуйте угоди про іменування для змінних, констант, функцій і класів
501497

502-
**TL;DR:** Use **_lowerCamelCase_** when naming constants, variables and functions, **_UpperCamelCase_** (capital first letter as well) when naming classes and **_UPPER_SNAKE_CASE_** when naming global or static variables. This will help you to easily distinguish between plain variables, functions, classes that require instantiation and variables declared at global module scope. Use descriptive names, but try to keep them short
498+
**Коротко:** Використовуйте **_lowerCamelCase_** для називання констант, змінних і функцій, **_UpperCamelCase_** (перша велика літера) для називання класів і **_UPPER_SNAKE_CASE_** для називання глобальних або статичних змінних. Це допоможе легко розрізняти звичайні змінні, функції, класи, які потребують інстанціювання, та змінні, оголошені на рівні глобального модуля. Використовуйте описові імена, але намагайтеся робити їх короткими.
503499

504-
**Otherwise:** JavaScript is the only language in the world that allows invoking a constructor ("Class") directly without instantiating it first. Consequently, Classes and function-constructors are differentiated by starting with UpperCamelCase
500+
**Інакше:** JavaScript — єдина мова у світі, яка дозволяє викликати конструктор ("Клас") напряму без попередньої інстанціювання. Як наслідок, класи та функції-конструктори відрізняються тим, що починаються з UpperCamelCase.
505501

506-
### 3.6 Code Example
502+
### 3.6 Приклад коду
507503

508504
```javascript
509-
// for global variables names we use the const/let keyword and UPPER_SNAKE_CASE
505+
// для глобальних змінних використовуємо ключові слова const/let і UPPER_SNAKE_CASE
510506
let MUTABLE_GLOBAL = "mutable value"
511507
const GLOBAL_CONSTANT = "immutable value";
512508
const CONFIG = {
513509
key: "value",
514510
};
515511

516-
// examples of UPPER_SNAKE_CASE convention in nodejs/javascript ecosystem
517-
// in javascript Math.PI module
512+
// приклади угоди UPPER_SNAKE_CASE у екосистемі nodejs/javascript
513+
// у модулі JavaScript Math.PI
518514
const PI = 3.141592653589793;
519515

520516
// https://github.com/nodejs/node/blob/b9f36062d7b5c5039498e98d2f2c180dca2a7065/lib/internal/http2/core.js#L303
521-
// in nodejs http2 module
517+
// у модулі nodejs http2
522518
const HTTP_STATUS_OK = 200;
523519
const HTTP_STATUS_CREATED = 201;
524520

525-
// for class name we use UpperCamelCase
521+
// для назв класів використовуємо UpperCamelCase
526522
class SomeClassExample {
527-
// for static class properties we use UPPER_SNAKE_CASE
523+
// для статичних властивостей класів використовуємо UPPER_SNAKE_CASE
528524
static STATIC_PROPERTY = "value";
529525
}
530526

531-
// for functions names we use lowerCamelCase
527+
// для назв функцій використовуємо lowerCamelCase
532528
function doSomething() {
533-
// for scoped variable names we use the const/let keyword and lowerCamelCase
529+
// для локальних змінних використовуємо ключові слова const/let і lowerCamelCase
534530
const someConstExample = "immutable value";
535531
let someMutableExample = "mutable value";
536532
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Використання ESLint та Prettier
2+
3+
### Порівняння ESLint та Prettier
4+
5+
Якщо ви відформатуєте цей код за допомогою ESLint, він лише видасть попередження про те, що рядок занадто широкий (залежить від налаштувань `max-len`). Prettier автоматично відформатує його для вас.
6+
7+
```javascript
8+
foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne(), noWayYouGottaBeKiddingMe());
9+
```
10+
11+
```javascript
12+
foo(
13+
reallyLongArg(),
14+
omgSoManyParameters(),
15+
IShouldRefactorThis(),
16+
isThereSeriouslyAnotherOne(),
17+
noWayYouGottaBeKiddingMe()
18+
);
19+
```
20+
21+
Джерело: [https://github.com/prettier/prettier-eslint/issues/101](https://github.com/prettier/prettier-eslint/issues/101)
22+
23+
### Інтеграція ESLint та Prettier
24+
25+
ESLint та Prettier перетинаються у функції форматування коду, але їх можна легко поєднати за допомогою інших пакетів, таких як [prettier-eslint](https://github.com/prettier/prettier-eslint), [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier) та [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier). Для отримання додаткової інформації про їхні відмінності, ви можете переглянути посилання [тут](https://stackoverflow.com/questions/44690308/whats-the-difference-between-prettier-eslint-eslint-plugin-prettier-and-eslint).
File renamed without changes.

0 commit comments

Comments
 (0)